Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame] | 1 | # |
Patrick Williams | 92b42cb | 2022-09-03 06:53:57 -0500 | [diff] [blame] | 2 | # Copyright OpenEmbedded Contributors |
| 3 | # |
Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame] | 4 | # SPDX-License-Identifier: GPL-2.0-only |
| 5 | # |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 6 | |
| 7 | class 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 | |
| 13 | class ClassRegistry(type, metaclass=ClassRegistryMeta): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 14 | """Maintain a registry of classes, indexed by name. |
| 15 | |
| 16 | Note that this implementation requires that the names be unique, as it uses |
| 17 | a dictionary to hold the classes by name. |
| 18 | |
| 19 | The name in the registry can be overridden via the 'name' attribute of the |
| 20 | class, and the 'priority' attribute controls priority. The prioritized() |
| 21 | method returns the registered classes in priority order. |
| 22 | |
| 23 | Subclasses of ClassRegistry may define an 'implemented' property to exert |
| 24 | control over whether the class will be added to the registry (e.g. to keep |
| 25 | abstract base classes out of the registry).""" |
| 26 | priority = 0 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 43 | return sorted(list(tcls.registry.values()), |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 44 | key=lambda v: (v.priority, v.name), reverse=True) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 45 | |
| 46 | def unregister(cls): |
| 47 | for key in cls.registry.keys(): |
| 48 | if cls.registry[key] is cls: |
| 49 | del cls.registry[key] |