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

login
register
mail settings
Submitter Christopher Larson
Date April 5, 2011, 7:08 p.m.
Message ID <8109d803d93d3101593825d3ee1abe4d7ac84ac4.1302030219.git.chris_larson@mentor.com>
Download mbox | patch
Permalink /patch/1951/
State New, archived
Headers show

Comments

Christopher Larson - April 5, 2011, 7:08 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>
---
 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]