Convert string to Python class object?
This could work:
import sys
def str_to_class(classname):
return getattr(sys.modules[__name__], classname)
You could do something like:
globals()[class_name]
You want the class Baz
, which lives in module foo.bar
. With Python 2.7,
you want to use importlib.import_module()
, as this will make transitioning to Python 3 easier:
import importlib
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
With Python < 2.7:
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = __import__(module_name, globals(), locals(), class_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
Use:
loaded_class = class_for_name('foo.bar', 'Baz')
Warning:
eval()
can be used to execute arbitrary Python code. You should never useeval()
with untrusted strings. (See Security of Python's eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>