Reputation: 1758
I am looking for a way to write an addon system for a Python 3 program that I am going to write. The program, after initializing everything else, would import the selected addons (Python scripts with code and/or functions) using a list that the user provided. The addons would then make the required changes to the program. A very simple implementation of the system would look like this:
for name in addons:
import name
Now, of course, this example does not work as the Python interpreter will try to import a module named 'name'. My question is, how do I use a variable to import a module? Or, if I can not do that, what would be the best way to implement an addon system?
Upvotes: 1
Views: 533
Reputation: 16711
I suggest using __import__()
as mentionend in Lennarts answer. Here is an example:
csv = __import__('csv')
Upvotes: 1
Reputation: 172219
A plugin system can be as simple as the plugins adding themselves or relevant objects/methods to a global list somewhere.
At the other end there are things like the zope.component architecture, where you can make your application into components where the plugins can not just add themselves to a list, but replace parts of the application. zope.component is cool. :-)
But yes, in any case you need somewhere to import the plugin/component.
In Python 3 I would use importlib.import_module()
. importlib
is available for Python 2 as well, and inclided in Python 2.7, but if you don't want more dependencies you might consider using __import__()
which exists in all versions of Python.
import_module()
is easier to use than __import__()
, as, which I always need to think before I use.
Upvotes: 3