Tried searching the site, but cannot find an answer to my problem:
Lets say I have a module, named mymodule.py that contains:
def a():
return 3
def b():
return 4 + a()
Then the following works:
import mymodule
print(mymodule.b())
However, when I try defining the module contents dynamically:
import imp
my_code = '''
def a():
return 3
def b():
return 4 + a()
'''
mymodule = imp.new_module('mymodule')
exec(my_code, globals(), mymodule.__dict__)
print(mymodule.b())
Then it fails in function b():
Traceback (most recent call last):
File "", line 13, in <module>
File "", line 6, in b
NameError: global name 'a' is not defined
I need a way to preserve the hierarchical namespace searching in modules, which seems to fail unless the module resides on disk.
Any clues as to whats the difference?
Thanks, Rob.