Add pysawsim.manager.SUBMODS and .IsSubclass and .get_manager.
authorW. Trevor King <wking@drexel.edu>
Wed, 20 Oct 2010 06:49:17 +0000 (02:49 -0400)
committerW. Trevor King <wking@drexel.edu>
Wed, 20 Oct 2010 06:49:17 +0000 (02:49 -0400)
IsSubclass is from my hooke.util.pluggable module.  get_manager() is
based on hooke.util.pluggable.submods() and .construct_odict().

.. _hooke: http://code.google.com/p/hooke/

pysawsim/manager/__init__.py

index 6bdba75991aa6abe27fe768dda113c447ce09507..f7b2cb53bfc3dc181b0b91df7b3d168c94b0a085 100644 (file)
@@ -24,6 +24,9 @@ from .. import invoke as invoke
 from .. import log
 
 
+SUBMODS = ['thread', 'pbs']
+
+
 class Job (object):
     """Job request structure for `JobManager`.
 
@@ -206,3 +209,59 @@ class JobManager (object):
 
     def _receive_job(self):
         raise NotImplementedError
+
+
+class IsSubclass (object):
+    """A safe subclass comparator.
+
+    Examples
+    --------
+
+    >>> class A (object):
+    ...     pass
+    >>> class B (A):
+    ...     pass
+    >>> C = 5
+    >>> is_subclass = IsSubclass(A)
+    >>> is_subclass(A)
+    True
+    >>> is_subclass = IsSubclass(A, blacklist=[A])
+    >>> is_subclass(A)
+    False
+    >>> is_subclass(B)
+    True
+    >>> is_subclass(C)
+    False
+    """
+    def __init__(self, base_class, blacklist=None):
+        self.base_class = base_class
+        if blacklist == None:
+            blacklist = []
+        self.blacklist = blacklist
+    def __call__(self, other):
+        try:
+            subclass = issubclass(other, self.base_class)
+        except TypeError:
+            return False
+        if other in self.blacklist:
+            return False
+        return subclass
+
+
+def get_manager(submod):
+    """
+    >>> get_manager('thread')
+    <class 'pysawsim.manager.thread.ThreadManager'>
+    >>> get_manager('wookie')
+    Traceback (most recent call last):
+      ...
+    AttributeError: 'module' object has no attribute 'wookie'
+    """
+    this_mod = __import__(__name__, fromlist=[submod])
+    sub_mod = getattr(this_mod, submod)
+    class_selector = IsSubclass(base_class=JobManager, blacklist=[JobManager])
+    for x_name in dir(sub_mod):
+        x = getattr(sub_mod, x_name)
+        if class_selector(x) == True:
+            return x
+    raise ValueError('no JobManager found in %s' % sub_mod.__name__)