namespace sharing (longish)

robin at illusionsexeculink.com.bbs robin at illusionsexeculink.com.bbs
Fri Jul 14 15:30:09 EDT 2000


I'm having a great deal of difficulty wrapping my head around the
namespace issue.

All I want to do is execute user-supplied (eg: arbitrary) functions
and have them share a namespace. So the first such function could
define some variables and later functions could read their values.

Simple. Or not?

I constructed the following test script:

# test.py BEGIN ###########
import pprint

if __name__ == "__main__":
	# seed the namespace
	namespace = {'var_main': 'hello'}

	# here lies my user module
	x = 'from test_lib import *'
	exec x in namespace
	del x

	# BEGIN KEY CODE
	# code to execute
	code1 = 'ret_one = one()'
	code2 = 'ret_two = two()'
	
	# compile it to be nice
	compiled1 = compile(code1, '<string>', 'exec')
	compiled2 = compile(code2, '<string>', 'exec')

	# go -- execute!
	exec compiled1 in namespace
	exec compiled2 in namespace
	# END KEY CODE

	# remove cruft from name space
	del code1, code2, compiled1, compiled2
	
	# what do we have?
	print
	print '0000000000000000000000000'
	pp = pprint.PrettyPrinter()
	print 'local => '
	pp.pprint( locals() )

	print 'global => '
	pp.pprint( globals().keys() )

# test.py END #############

Then, the user module could look like:

# test_lib.py BEGIN ###########
def one():
	import pprint

	# define a variable local to this routine
	var_one = 'in one'
	
	# check out our environment -- any sign of namespace? no??
	print
	print '1111111111111111111111111'
	pp = pprint.PrettyPrinter()
	print ' local => '
	pp.pprint( locals() )
	print 'global => '
	pp.pprint( globals().keys() )

	return 'one'
	
def two():
	import pprint

	# same as above -- for now
	# later this will catch variables defined in one()
	var_two = 'in two'
	
	print
	print '2222222222222222222222222'
	pp = pprint.PrettyPrinter()
	print ' local => '
	pp.pprint( locals() )
	
	print 'global => '
	pp.pprint( globals().keys() )

	return 'two'
# test_lib.py END #############

Then I tried a variation of test.py using the eval function in place
of the exec statement:

	# BEGIN KEY CODE
	code1 = 'one()'
	code2 = 'two()'
	
	compiled1 = compile(code1, '<string>', 'eval')
	compiled2 = compile(code2, '<string>', 'eval')
	
	ret_one = eval(compiled1, namespace)
	ret_two = eval(compiled2, namespace)
	# END KEY CODE

The results?

The namespace appears to have no effect on the user routines. They
cannot see var_main. Both methods produce the same (null) results.

How do I do this?

-----
robin                          robin at illusionsexeculink.com
media artist /                 remove illusions to reply
information architect          www.execulink.com/~robin/

"We told it about general relativity and gravity, the kind of people
that overcome hardships."



More information about the Python-list mailing list