Automatically loading and initialising objects from a plugins directory

Dave Challis dsc at ecs.soton.ac.uk
Tue Jul 22 12:15:56 EDT 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Diez B. Roggisch wrote:
> 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

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()

Cheers,
Dave


- --
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                     ><>                       o  )           <><
                                              .   (    (
 )    Dave Challis                            <>< )    )          ><>
_(__dsc at ecs.soton.ac.uk___________________________(____(__________________
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIhge8v26GZvAVVFERAh86AJ91DVYPPZ/1x3rjoezFL1P5FXuHNwCZAXdr
DgjzmTNV1/H8vcQ/2Hax3js=
=ZAtM
-----END PGP SIGNATURE-----



More information about the Python-list mailing list