Convert string to Python class object?


Question

Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:

class Foo:
    pass

str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>

Is this, at all, possible?

1
161
10/15/2018 9:18:42 AM

Accepted Answer

Warning: eval() can be used to execute arbitrary Python code. You should never use eval() with untrusted strings. (See Security of Python's eval() on untrusted strings?)

This seems simplest.

>>> class Foo(object):
...     pass
... 
>>> eval("Foo")
<class '__main__.Foo'>
100
4/4/2018 5:20:09 PM

This could work:

import sys

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon