Reputation: 1094
I'm probably not using the right terminology, but I'm learning python and I'm trying something that I can easily do in Lua:
def fire(self):
return self._loadModule()[self._entrypoint]() #subscripting the module raises an error
def _loadModule(self):
return __import__(self._module)
I want to load the module and then call an arbitrary function inside that module. What is correct way to do this?
EDIT: Module and entry point names are determined at runtime.
Upvotes: 0
Views: 287
Reputation: 27236
If I understand it right; a completely useless example:
def my_sqrt(num):
import math #load a module
return math.sqrt(num) #call the function
From string:
>>> def f(module, function, *args):
... return(getattr(__import__(module), function)(*args))
...
>>> f("math", "sqrt", 2)
1.4142135623730951
Upvotes: 3
Reputation: 107676
mod = 'os'
func = 'listdir'
m = __import__(mod)
f = getattr(m, func)
import os
assert f is os.listdir
Upvotes: 1