classutils.py 1.5 KB

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