0

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

ssj
  • 1,737
  • 2
  • 16
  • 28

2 Answers2

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