Dynamically Load Python Modules or Classes

Or how to instantiate a Python class from a string using importlib.

There is an official Python module, importlib, that allows you to import any Python module from a string. You may need to install it if you run a Python version older than 2.7.

Loading dynamically a class with importlib is easy, first you have to actually load the module with import_module, and finally you can retrieve the class with getattr.

Here is a working function that takes a string like module.submodule.MyClass as argument and returns the class:

import importlib

def load_class(full_class_string):
    dynamically load a class from a string

    class_data = full_class_string.split(".")
    module_path = ".".join(class_data[:-1])
    class_str = class_data[-1]

    module = importlib.import_module(module_path)
    # Finally, we retrieve the Class
    return getattr(module, class_str)

Your feedback

Don't hesitate if you have any questions, suggestions or improvements !

You should follow me on Twitter

Share this article

Tip with Bitcoin

Tip me with Bitcoin and vote for this post!


Leave a comment

© Thomas Sileo. Powered by Pelican and hosted by DigitalOcean.