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'>

Updated on: 09-Sep-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements