1# 2# Copyright OpenEmbedded Contributors 3# 4# SPDX-License-Identifier: GPL-2.0-only 5# 6 7class ClassRegistryMeta(type): 8 """Give each ClassRegistry their own registry""" 9 def __init__(cls, name, bases, attrs): 10 cls.registry = {} 11 type.__init__(cls, name, bases, attrs) 12 13class ClassRegistry(type, metaclass=ClassRegistryMeta): 14 """Maintain a registry of classes, indexed by name. 15 16Note that this implementation requires that the names be unique, as it uses 17a dictionary to hold the classes by name. 18 19The name in the registry can be overridden via the 'name' attribute of the 20class, and the 'priority' attribute controls priority. The prioritized() 21method returns the registered classes in priority order. 22 23Subclasses of ClassRegistry may define an 'implemented' property to exert 24control over whether the class will be added to the registry (e.g. to keep 25abstract base classes out of the registry).""" 26 priority = 0 27 def __init__(cls, name, bases, attrs): 28 super(ClassRegistry, cls).__init__(name, bases, attrs) 29 try: 30 if not cls.implemented: 31 return 32 except AttributeError: 33 pass 34 35 try: 36 cls.name 37 except AttributeError: 38 cls.name = name 39 cls.registry[cls.name] = cls 40 41 @classmethod 42 def prioritized(tcls): 43 return sorted(list(tcls.registry.values()), 44 key=lambda v: (v.priority, v.name), reverse=True) 45 46 def unregister(cls): 47 for key in cls.registry.keys(): 48 if cls.registry[key] is cls: 49 del cls.registry[key] 50