Short version:
Say I have a string str and a file functions.py from which I would like to import a method whose name is stored in str.
How do I go about it? I would like something like:
from functions.py import str
but have str evaluated and not to import the method 'str' (which doesn't exist).
After some googling I came as close (I hope) as:
func_name = str
_tmp = __import__('functions.py', globals(), locals(), ['func_name'], -1)
func = ???? <what to put here?>
Thanks in advance.
EDIT: TMI.
3 Answers 3
Assuming your code to import the module into _tmp works then the final step is simply:
func = getattr(_tmp, func_name)
Comments
The getattr method gives you an attribute of a given object. Since global functions are attributes of the module they are in, you can use this:
import functions
funcName = 'doSomething'
f = getattr(functions, funcName)
f(123)
There is no need to use __import__, as that's usually needed only when you don't know the module name in advance.
Comments
If your goal is to save memory by only importing the functions you need, don't bother; even if you used the from ... import ... construct, Python still imports the whole module, just that it only adds to the current dictionary those members that you explicitly requested (the others are still in memory, just that they're not accessible directly).
With that in mind, I would do something along these lines:
import functions
the_name = self.name.lower() + str(i)
the_func = getattr(functions, the_name)
functionsand notfunctions.py.