blob: ec3f6ad720fd18fc6f9cea451387f8e6a514fbf7 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williams92b42cb2022-09-03 06:53:57 -05002# Copyright OpenEmbedded Contributors
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
5#
Patrick Williamsc0f7c042017-02-23 20:41:17 -06006
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):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050014 """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
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027 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):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060043 return sorted(list(tcls.registry.values()),
Brad Bishop6e60e8b2018-02-01 10:27:11 -050044 key=lambda v: (v.priority, v.name), reverse=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050045
46 def unregister(cls):
47 for key in cls.registry.keys():
48 if cls.registry[key] is cls:
49 del cls.registry[key]