Tested on:RPi3; Raspbian Stretch; Python3
Prerequisites:Raspberry Pi with Raspbian Jessie and internet connection (see steps 1-7 in the Introduction)
0

Loading Python modules dynamically with importlib and getattr

Sometimes it’s useful to add program components dynamically, e.g. for extending a base variant with additional capabilities. Ideally, components are just put into subdirectories directories and then Python loads all components available by means of importlib and getattr.

Directory layout
All components are stored in ./components/ in a subdirectory. The pattern is components/xyz/xyz.py with a class Xyz in the script xyz.py. Create two dummy modules with

Dynamic import
Download the demo script and run it with

The names of the imported components are printed to the terminal:

Code explained
These statements import a component dynamically:

importlib.import_module imports a component according to component_path. component_path is formatted as Python3 import path following the pattern devices.xyz.xyz. The component Xyz is then initialized with getattr.

Full script
Click on Full Script to show all of the code.

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.

Comment

Time limit is exhausted. Please reload CAPTCHA.