Computer >> Computer tutorials >  >> Programming >> Python

How to convert a string to a Python class object?


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.

Example

class Foobar:
    pass
print eval("Foobar")
print type(Foobar)

Output

 __main__.Foobar
<type 'classobj'>

Another way to convert a string to class object is as follows

Example

import sys
class Foobar:
    pass
def str_to_class(str):
    return getattr(sys.modules[__name__], str)
print str_to_class("Foobar")
print type(Foobar)

Output

__main__.Foobar
<type 'classobj'>