[Python] help designing a plugin system

Started by
0 comments, last by the_edd 13 years, 6 months ago
Hi folks,

I'm writing a little tool in Python. I'd like to implement a plugin mechanism through which power-users can extend the tool's functionality.

Ideally, I was thinking that when swarm (working title of the tool) is invoked, it would look for python packages under the system- and user-level site-packages directories and each plugin could either be contained in a directory or a zip file.

So the foobar plugin would be found if either of the following files existed:

.../site-packages/swarm/plugins/foobar/plugin.py
.../site-packages/swarm/plugins/foobar.zip/plugin.py

Each plugin.py would export certain hooks expected of a plugin.

The idea behind giving each plugin its own directory or zip file is that the implementation of that plugin could be spread across multiple python modules if the author so-desired. Then the plugins wouldn't step on each others' toes, at least as far as the filesystem is concerned. The idea behind allowing zip files is that you would be able to develop the plugin inside a regular directory and simply zip it up when it's ready for distribution.

Hopefully that sounds semi-reasonable so far. So now the problem: if I'm the author of the foobar plugin and I have a module called utilities(.py/.pyc) that I'd like to include as part of the plugin, I'd like to be able to say "import utilities" in foobar's plugin.py.

As far as I know, this can only be achieved by adding .../site-packages/swarm/plugins/foobar to sys.path. But this somewhat defeats the point of giving each plugin their own directory, since now if another plugin does "import utilities", it might end up with the module provided with foobar.

So my questions are:

1. Is there a way around this?
2. Or is there a better way, entirely?

I'd like to avoid the situation where each plugin author has to do "import swarm.plugins.foobar.utilities", but maybe that's asking for too much?
Advertisement
To answer my own question, the easiest way of doing what I want seems to be to replace __builtin__.__import__ with a function that looks to see if a module is being imported from inside a plugin file.

My replacement was based off of the "knee" demo code in the Python repository.

This topic is closed to new replies.

Advertisement