Dynamically Instantiating Classes in Python

A common design pattern is to define a class or list of classeses in configuration such that at runtime the classes can be dynamically instantiated.

I’ve done this before in many other languages and had need to do so today in Python (2.7.11)

It seems as though the clean way to do so is by using the Pyton importlib module.  By using it, it enables you to cleanly dynamically import sub modules

Following is an example:

    import importlib

    klass_1_module = ‘some.module.name’
    klass_1_classname = ‘KlassNameOne’

    klass_2_module = ‘klass2module’
    klass_2_classname = ‘KlassNameOne’

    Klass1 = getattr(importlib.import_module(klass_1_module), klass_1_classname)
    klass1_instance = Klass1()

    Klass2 = getattr(importlib.import_module(klass_2_module), klass_2_classname)
    klass2_instance = Klass1(‘some_arg’)

Leave a Reply