Joe Ray

Principal Engineer

Dynamically loading classes from modules in Python

I was working on a bit of code today where I wanted to be able to dynamically load a class from a module that’s specified by some external configuration.

Let’s say you have a package called widgets and within that, a series of modules (e.g. mail, sms, irc etc.) that contain classes which all inherit from the superclass WidgetAPI.

To load the widgets.mail.WidgetAPI class when given the string 'mail' by the user, you could do:

import inspect
import importlib

from widgets import WidgetAPI

def find_widget(widget_type):
    try:
        module = importlib.import_module('widgets.{0}'.format(widget_type))
        for x in dir(module):
            obj = getattr(module, x)

            if inspect.isclass(obj) and issubclass(obj, WidgetAPI) and obj is not WidgetAPI:
                return obj
    except ImportError:
        return None

if __name__ == '__main__':
    print(find_widget('mail'))
    print(find_widget('blah'))

This will produce the output:

<class 'widgets.mail.MailWidget'>
None

Contact Me

I love a good conversation! E-mail me (encrypted if you want) or find me on Twitter, LinkedIn and GitHub.