Sometimes you want to import one of many configuration files, each of which had different values for the same named variables, dicts, etc.
You can't just do this:
def mother_function(module, *args, **kwargs):
from module import variable
return variable
def call_home_to_mamma():
import module_42
return mother_function(module_42)
The explanation as to why this doesn't work is above my pay grade, and involves closures and namespaces. What I found worked was to call the mother function with 'module_name' as a string argument, then dyamically import the particular variable when I really needed it:
def mother_function(module_name, *args, **kwargs):
exec('from %s import %s' % (module_name, variable))
variable = eval(variable)
return variable
def call_home_to_mamma():
import module_42
return mother_function(module_42.__name__)
Bingo.... you have dyamic import of any variable you want, from an imported module as determined at runtime.