0

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

3
  • define mapping as mentioned on above linked answer or if the function is global globals()[func_name](params,..) where func_name is string. Commented Dec 25, 2013 at 3:41
  • @IgnacioVazquez-Abrams I do not think that solution is elegant. Commented Dec 25, 2013 at 4:11
  • 1
    Beware of what you may think is "elegant" in Python, especially if you are coming from other languages. Commented Dec 25, 2013 at 6:02

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

sys.module can only work fine for python standard library, not for user-define module
@whatout I was already editing my answer :) Please check the update :)
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.

2 Comments

I think question is about using string name to call function.
hmm, could be. It's not very clear....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.