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 use eval() 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]

Leave a Reply

Your email address will not be published. Required fields are marked *