Can you use a string to instantiate a class? Can you use a string to instantiate a class? python python

Can you use a string to instantiate a class?


If you wanted to avoid an eval(), you could just do:

id = "1234asdf"constructor = globals()[id]instance = constructor()

Provided that the class is defined in (or imported into) your current scope.


Not sure this is what you want but it seems like a more Pythonic way to instantiate a bunch of classes listed in a string:

class idClasses:    class ID12345:pass    class ID01234:pass# could also be: import idClassesclass ProcessDirector:    def __init__(self):        self.allClasses = []    def construct(self, builderName):        targetClass = getattr(idClasses, builderName)        instance = targetClass()        self.allClasses.append(instance)IDS = ["ID12345", "ID01234"]director = ProcessDirector()for id in IDS:    director.construct(id)print director.allClasses# [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>]


Never use eval() if you can help it. Python has so many better options (dispatch dictionary, getattr(), etc.) that you should never have to use the security hole known as eval().