Convert string to Python class object?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Convert String To Python Class Object?
00:25 Answer 1 Score 204
00:40 Accepted Answer Score 152
01:05 Answer 3 Score 146
01:17 Answer 4 Score 119
01:59 Answer 5 Score 42
02:41 Thank you
--
Full question
https://stackoverflow.com/questions/1176...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Convert String To Python Class Object?
00:25 Answer 1 Score 204
00:40 Accepted Answer Score 152
01:05 Answer 3 Score 146
01:17 Answer 4 Score 119
01:59 Answer 5 Score 42
02:41 Thank you
--
Full question
https://stackoverflow.com/questions/1176...
--
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 useeval()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')