Plugins in Python

David Bolen db3l at fitlinxx.com
Tue Jun 12 19:26:16 EDT 2001


David LeBlanc <whisper at oz.nospamnet> writes:

> How would one generally code something that would look at some dir (or 
> list of dirs), and dynamically load .py or .pyc modules found there that 
> where not previously known to the program. Obviously following a standard 
> API...

I tend to make plugins for an application a package.

One approach is that the __init__ file in the package can inspect the
package directory for other modules, and then use __import__ to import
them.  I normally then populate a well-known dictionary within the
__init__ module that applications can use to determine what plugins
were loaded.  You can also decide to set up the modules for lazy
loading using a proxy class if you want to avoid the overhead of
actually importing the plugin until needed.

Note that one major negative with this approach is that it confuses
Python installation tools like py2exe and installer, as they can't
follow the dynamic importing, and also because the directory structure
may not be similar during execution.

So in the cases that I need to package things, I instead write my
__init__ such that it contains explicit imports for supported plugins,
but nothing more.  Then instead of looping through the filesystem, I
loop through my local dictionary looking for modules, and then import
them (or call well defined entry points in them to let them identify
what they support).  This does mean they all get imported, but it
works regardless of directory structure, and can be packaged.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list