0

How do I load a python module, that is not built in. I'm trying to create a plugin system for a small project im working on. How do I load those "plugins" into python? And, instaed of calling "import module", use a string to reference the module.

1

1 Answer 1

1

Have a look at importlib

Option 1: Import an arbitrary file in an arbiatrary path

Assume there's a module at /path/to/my/custom/module.py containing the following contents:

# /path/to/my/custom/module.py

test_var = 'hello'

def test_func():
    print(test_var)

We can import this module using the following code:

import importlib.machinery
myfile = '/path/to/my/custom/module.py'
sfl = importlib.machinery.SourceFileLoader('mymod', myfile)
mymod = sfl.load_module()

The module is imported and assigned to the variable mymod. We can then access the module's contents as:

mymod.test_var
# prints 'hello' to the console

mymod.test_func()
# also prints 'hello' to the console

Option 2: Import a module from a package

Use importlib.import_module

For example, if you want to import settings from a settings.py file in your application root folder, you could use

_settings = importlib.import_module('settings')

The popular task queue package Celery uses this a lot, rather than giving you code examples here, please check out their git repository

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.