if I have a string like 'module.function', How can I execute function just by one step?
likesomefunction('os.error','args')
-
define mapping as mentioned on above linked answer or if the function is global globals()[func_name](params,..) where func_name is string.Mutant– Mutant2013-12-25 03:41:24 +00:00Commented Dec 25, 2013 at 3:41
-
@IgnacioVazquez-Abrams I do not think that solution is elegant.ssj– ssj2013-12-25 04:11:09 +00:00Commented Dec 25, 2013 at 4:11
-
1Beware of what you may think is "elegant" in Python, especially if you are coming from other languages.Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2013-12-25 06:02:35 +00:00Commented Dec 25, 2013 at 6:02
Add a comment
|
2 Answers
You can dynamically get the modules using sys.modules and then you can use getattr to get the attributes from the module, like this
import sys
func = "os.error"
module, function = func.split(".", 1)
getattr(sys.modules[module], function)()
sys.modules can give only the modules which are already loaded. So, if you want to load a module dynamically you can use __import__ function like this
For example,
module, function = "math.factorial".split(".", 1)
print getattr(__import__(module), function)(5)
Output
120
2 Comments
ssj
sys.module can only work fine for python standard library, not for user-define module
thefourtheye
@whatout I was already editing my answer :) Please check the update :)