How to load Python modules dynamically

Andy Barnes
4 min readDec 24, 2023

This post will cover why you might want to load Python modules dynamically and how to do it if you do.

Why?

Dynamic module imports are useful if you need to import modules that you do not know the name of when writing your code and therefore cannot use the traditional from foo import bar syntax.

You might need this if you have an application that, at runtime, needs to import or parse a list of additional modules to provide or extend some functionality. Or, you have an application with many modules but only certain ones are used at any particular time.

As a real-world example, I use this approach in some financial trading software I maintain. There are hundreds of strategy modules which can be imported, but only a handful are used at any one time, depending on what portfolio of strategies is traded. As I don’t want the core of my software to be cluttered with loads of unused imports, I parse a configuration file which lists the names of the modules I want to run live. These modules are then imported dynamically on start-up.

Let’s say you have the urge to create an application to provide a range of awesome different formatters for people to use. Your project layout looks like this:

super-formatter/
__init__.py
format.py
base_formatter.py…

--

--

Andy Barnes

A software engineer and algorithmic trader. Passion for Python and Financial markets.