The Python Oracle

Convert string to Python class object?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Question
00:35 Accepted answer (Score 145)
00:59 Answer 2 (Score 191)
01:12 Answer 3 (Score 140)
01:24 Answer 4 (Score 115)
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/1176...

Accepted answer links:
[Security of Python's eval() on untrusted strings?]: https://stackoverflow.com/q/661084/33579...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 205


This could work:

import sys

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



ACCEPTED ANSWER

Score 152


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



ANSWER 3

Score 148


You could do something like:

globals()[class_name]



ANSWER 4

Score 120


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