Patchwork [1/9] oe.classutils: add module

login
register
mail settings
Submitter Otavio Salvador
Date June 17, 2011, 2:51 p.m.
Message ID <a322eed8819621c33cc120bd3200a29006476b67.1308322247.git.otavio@ossystems.com.br>
Download mbox | patch
Permalink /patch/6053/
State New, archived
Headers show

Comments

Otavio Salvador - June 17, 2011, 2:51 p.m.
From: Chris Larson <chris_larson@mentor.com>

This adds a ClassRegistry utility metaclass, as maintaining a class registry
is a fairly common thing to do.

Signed-off-by: Chris Larson <chris_larson@mentor.com>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
---
 meta/lib/oe/classutils.py |   24 ++++++++++++++++++++++++
 1 files changed, 24 insertions(+), 0 deletions(-)
 create mode 100644 meta/lib/oe/classutils.py

Patch

diff --git a/meta/lib/oe/classutils.py b/meta/lib/oe/classutils.py
new file mode 100644
index 0000000..855d2fa
--- /dev/null
+++ b/meta/lib/oe/classutils.py
@@ -0,0 +1,24 @@ 
+class ClassRegistry(type):
+    """Maintain a registry of classes, indexed by name.
+
+    The name in the registry can be overridden via the 'name' attribute of the
+    class, and the 'priority' attribute controls priority.  The prioritized()
+    method returns the registered classes in priority order."""
+    registry = {}
+    priority = 0
+
+    def __init__(cls, name, bases, attrs):
+        super(ClassRegistry, cls).__init__(name, bases, attrs)
+        if not hasattr(cls, name):
+            cls.name = name
+        cls.registry[cls.name] = cls
+
+    @classmethod
+    def prioritized(tcls):
+        return sorted(tcls.registry.values(),
+                      key=lambda v: v.priority, reverse=True)
+
+    def unregister(cls):
+        for key in cls.registry.keys():
+            if cls.registry[key] is cls:
+                del cls.registry[key]