When writing a new program in python, I often find myself using the same
pattern over and over, and wanted to document it here. The idea is that you
have some core functionality of the program, and loadable modules to expand
the functionality, with only some of the modules being loaded at runtime.
These modules are single files inside a modules/ directory, contain a single
Module() class (and optionally others depending on what the module needs), and
some other functionality that the core of your program will use. This pattern
lets you specify which modules to load in a configuration file, and load them
up on demand, passing in some configuration to the module.
First, the code to load the modules:
This gives you a list of module objects in modules, and you can then call
methods on those modules (I tend to have a run() method or have the __init__
method set up callbacks for various events depending on the program’s
A module itself would be a single python file inside modules (e.g.
modules/example.py) and look something like this:
You also need to make sure your modules directory has an __init__.py file
(it can be blank) so that python knows the directory contains modules.
This pattern can be expanded on in various ways depending on the needs of your
program, but for anywhere where you have pluggable functionality, it works