how to dynamically create an instance of a class in python?

This worked for me:

from importlib import import_module

class_str: str = 'A.B.YourClass'
try:
    module_path, class_name = class_str.rsplit('.', 1)
    module = import_module(module_path)
    return getattr(module, class_name)
except (ImportError, AttributeError) as e:
    raise ImportError(class_str)

This is often referred to as reflection or sometimes introspection. Check out a similar questions that have an answer for what you are trying to do:

Does Python Have An Equivalent to Java Class forname

Can You Use a String to Instantiate a Class in Python


You can often avoid the string processing part of this entirely.

import foo.baa 
import foo.AA
import foo

classes = [ foo.baa.a, foo.daa.c, foo.AA ]

def save(theClass, argument):
   aa = theClass()
   aa.save(argument)

save(random.choice(classes), arg)

Note that we don't use a string representation of the name of the class.

In Python, you can just use the class itself.


Assuming you have already imported the relevant classes using something like

from [app].models import *

all you will need to do is

klass = globals()["class_name"]
instance = klass()

Tags:

Python