1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

I suggest using __import__() as mentionend in Lennarts answer. Here is an example:

csv = __import__('csv')

4 Comments

SyntaxError: invalid syntax
@ThomasK - right, my approach with format string was wrong, so I changed it to an example using __import__().
By the way: Would it better to delete my answer and add the example to Lennarts answer? Sorry, I'm just new here ...
I'm not really sure what's accepted practice if you get an answer completely wrong. If you change it, you have to hope people remember to remove their downvotes (as I've done now). Ideally, test your suggestion a bit before you post it ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.