Convert string to Python class object?
Convert string to Python class object?
This could work:
import sys
def str_to_class(classname):
return getattr(sys.modules[__name__], classname)
Warning:
eval()
can be used to execute arbitrary Python code. You should never useeval()
with untrusted strings. (See Security of Pythons eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval(Foo)
<class __main__.Foo>
Convert string to Python class object?
You could do something like:
globals()[class_name]