Automatically loading and initialising objects from a plugins directory
Fredrik Lundh
fredrik at pythonware.com
Tue Jul 22 12:28:28 EDT 2008
Dave Challis wrote:
> Thanks for that, it helped as a starting point. I had some trouble with
> using issubclass though (issubclass(Plugin, Plugin) returns true), which
> was complicating things.
>
> I modified your code to the following instead (which may well have it's
> own pitfalls I'm not aware of!):
>
> for name in dir(plugin):
> thing = getattr(plugin, name)
> if hasattr(thing, '__bases__') and \
> getattr(thing, '__bases__')[0] == Plugin:
> thing()
so now you're no longer supporting mixins and multiple-level
inheritance? why not just tweak Diez' example a little:
for name in dir(plugin):
thing = getattr(plugin, name)
# make sure this is a plugin
try:
if thing is Plugin:
continue
if not issubclass(thing, Plugin):
continue
except ValueError: # issubclass sucks
continue # not a class
thing() # probably needs error handling around this
(I also moved the thing call out of the thing validation part, to allow
you to distinguish between ValueErrors caused by issubclass and errors
caused by things)
(btw, another approach would be to use a metaclass to make Plugin
classes register themselves on import)
</F>
More information about the Python-list
mailing list