Automatically loading and initialising objects from a plugins directory

Diez B. Roggisch deets at nospam.web.de
Tue Jul 22 08:42:18 EDT 2008


Dave Challis wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> I'm trying to write some code which:
> 1. Finds all modules in a plugin directory
> 2. Imports those modules
> 3. Creates an instance of each object defined in the module (each module
> will contain exactly 1 object, which is a subclass of 'Plugin')
> 
> The closest I've come so far is with something like:
> 
> In plugin.py:
> # taken from http://docs.python.org/lib/built-in-funcs.html
> def my_import(name):
>     mod = __import__(name)
>     components = name.split('.')
>     for comp in components[1:]:
>         mod = getattr(mod, comp)
>     return mod
> 
> def import_plugins():
>     mods = []
>     for filename in os.listdir('/plugins'):
>         if filename.endswith('.py'):
>             name = os.path.splitext(filename)[0]
>             mods.append(my_import('plugins.' + name))
>     return mods
> 
> class Plugin(object):
>     pass
> 
> 
> In plugins/exampleplugin.py:
> class ExamplePlugin(Plugin):
>     def __init__(self):
>         pass
> 
> 
> Calling import_plugins() then gives me a list containing references to
> modules.
> 
> How can I loop through that list and create an instance of whatever
> object was defined within the module? (In this case I'd want to
> construct an instance of ExamplePlugin)


Like this:

for name in dir(plugin):
    thing = getattr(plugin, name)
    try:
       if issubclass(thing, Plugin):
          thing()
    except ValueError: # issubclass sucks
       pass

Diez



More information about the Python-list mailing list