namespace sharing (longish)
Greg Ewing
see at my.signature
Thu Jul 20 22:25:54 EDT 2000
"robin"@illusionsexeculink.com.bbs at openbazaar.net wrote:
>
> All I want to do is execute user-supplied (eg: arbitrary) functions
> and have them share a namespace.
Your example doesn't work because your one() and two() functions
live in a separate module. The global namespace of a function
defined in a module is always the namespace of that module,
regardless of how the function gets called.
One way to do what you want is to compile() the function
definition itself:
namespace = {'var_main': 'hello', '__builtins__': {}}
source = """
def one():
global var_main
print var_main
var_main = 'spam'
"""
code = compile(source, "", "exec")
exec code in namespace # defines the function within namespace
print namespace
namespace["one"]() # call the function
print namespace
--
Greg Ewing, Computer Science Dept, University of Canterbury,
Christchurch, New Zealand
To get my email address, please visit my web page:
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list