class / module introspection?

Brian Munroe brian.e.munroe at gmail.com
Thu Apr 3 00:36:42 EDT 2008


On Apr 2, 2:26 pm, 7stud <bbxx789_0... at yahoo.com> wrote:

>
> You don't need that helper function, which is a little tricky to
> follow:
>

Well, I appreciate the code sharing you did, but the helper function
is nice and compact, and I didn't have much trouble following it.  I
ended up doing the following in the backends/__init__.py:

import os
availableBackendsList = []

for module in os.listdir(__path__[0]):
    if not module.startswith("__") and not module.startswith("."):
        availableBackendsList.append("backends." + module)

def subpackage_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

def get_available_backends():
    return map(subpackage_import, availableBackendsList)

In then in my application code, it becomes a simple matter of:

import backends

for x in backends.get_available_backends():
    print x.PLUGIN_NAME
    be = x.Backend()
    print be.getStatus()

Basically, I borrowed a page out of Dive into Python[1] and mapped
each module object (system1, system2, ... systemN) to a list.


[1] - Thanks Mark! - http://www.diveintopython.org/functional_programming/all_together.html



More information about the Python-list mailing list