hierarchical namespaces in custom python modules -
tried searching site, cannot find answer problem:
lets have module, named mymodule.py contains:
def a(): return 3 def b(): return 4 + a() then following works:
import mymodule print(mymodule.b()) however, when try defining 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 fails in function b():
traceback (most recent call last): file "", line 13, in <module> file "", line 6, in b nameerror: global name 'a' not defined i need way preserve hierarchical namespace searching in modules, seems fail unless module resides on disk.
any clues whats difference?
thanks, rob.
you're close. need tell exec work in different namespace (see note @ bottom python 3.x):
exec my_code in mymodule.__dict__ full example:
import imp my_code = ''' def a(): return 3 def b(): return 4 + a() ''' mymodule = imp.new_module('mymodule') exec my_code in mymodule.__dict__ print(mymodule.b()) this said, i've not used before, i'm not sure if there weird side-effects this, looks works me.
also, there's small blurb 'exec in ...' in python docs here: http://docs.python.org/reference/simple_stmts.html#the-exec-statement
update
the reason original attempt didn't work correctly passing current module's globals() dictionary, different globals() new module should use.
this exec line works (but isn't pretty 'exec in ...' style):
exec(my_code, mymodule.__dict__, mymodule.__dict__) update 2: since exec function in python 3.x, has no 'exec in ...' style, line above must used.
Comments
Post a Comment