Mike Orr avatar Mike Orr committed f1a5b0c

``subclasses_only()`` helper. Bring changelog up to date.

Comments (0)

Files changed (3)

 
 tip (development version)
 -------------------------
+* webhelpers.misc:
+
+  - New helper ``subclasses_only`` to extract the subclasses of an abstract
+    base class from a module or iterable.
+
+* webhelpers.pylonslib.grid:
+
+  - Bugfixes.
 
 1.0b3 (2009-12-29)
 ------------------

tests/test_misc.py

+from nose.tools import eq_
+
+from webhelpers.misc import *
+
+class DummyBase(object):  pass
+class Subclass1(DummyBase):  pass
+class Subclass2(DummyBase):  pass
+
+def test_subclasses_only():
+    subclasses = subclasses_only(DummyBase, globals())
+    subclasses.sort()
+    control = [Subclass1, Subclass2]
+    eq_(subclasses, control)

webhelpers/misc.py

 """
 
 import itertools
+import types
 
 def all(seq, pred=None):
     """Is ``pred(elm)`` true for all elements?
     except Exception:
         return None
 
+def subclasses_only(class_, it):
+    """Extract the subclasses of a class from a module, dict, or iterable.
+
+    Return a list of subclasses found. The class itself will not be included.
+    This is useful to collect the concrete subclasses of an abstract base
+    class.
+
+    ``class_`` is a class.
+
+    ``it`` is a dict or iterable. If a dict is passed, examine its values,
+    not its keys. To introspect the current module, pass ``globals()``. To
+    introspect another module or namespace, pass
+    ``vars(the_module_or_namespace)``.
+
+    Example: to collect all subclasses in the current module::
+    >>> subclasses_only(MyBaseClass, globals())   # doctest: +SKIP
+    [Subclass1, Subclass2]
+    """
+    if isinstance(it, dict):
+        it = it.itervalues()
+    class_types = (type, types.ClassType)
+    return [x for x in it if isinstance(x, class_types) and 
+        issubclass(x, class_) and x is not class_]
+
 class DeclarativeException(Exception):
     """A simpler way to define an exception with a fixed message.
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.