if I have a string like 'module.function', How can I execute function just by one step?
likesomefunction('os.error','args')
Asked
Active
Viewed 168 times
0

ssj
- 1,737
- 2
- 16
- 28
-
define mapping as mentioned on above linked answer or if the function is global globals()[func_name](params,..) where func_name is string. – Mutant Dec 25 '13 at 03:41
-
@IgnacioVazquez-Abrams I do not think that solution is elegant. – ssj Dec 25 '13 at 04:11
-
1Beware of what you may think is "elegant" in Python, especially if you are coming from other languages. – Ignacio Vazquez-Abrams Dec 25 '13 at 06:02
2 Answers
1
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

thefourtheye
- 233,700
- 52
- 457
- 497
-
sys.module can only work fine for python standard library, not for user-define module – ssj Dec 25 '13 at 04:16
-
@whatout I was already editing my answer :) Please check the update :) – thefourtheye Dec 25 '13 at 04:17
0
All you need to do is
from module import function
and you'll be able to call
function(x, y, z)
in your code.

MattDMo
- 100,794
- 21
- 241
- 231