Following this answer, I am using imp.new_module
and exec
to dynamically load a module and extract functions from it. However, when I store the module in a local variable, functions from it get broken. Here is an example:
import imp
mod = None
func = None
code = """
a = 42
def func():
print a
"""
def main():
#global mod
global func
mod = imp.new_module("modulename")
exec code in mod.__dict__
func = mod.func
main()
func()
Executing this with Python 2.7.3 yields None
: codepad. After uncommenting global mod
line, making mod
global, the function works as expected and prints 42: codepad.
What am I missing? Why does the behaviour change when module is stored in a local variable?