0

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

ssj
  • 1,677
  • 1
  • 16
  • 26

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
  • 221,210
  • 51
  • 432
  • 478
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
  • 96,286
  • 20
  • 232
  • 224