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

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


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()


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


This worked for me:

from importlib import import_moduleclass_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)