Convert string to Python class object?

Solution 1:

This could work:

import sys

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

Solution 2:

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

Solution 3:

You could do something like:

globals()[class_name]

Solution 4:

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