Replacing globals in exec by custom class

DevPlayer devplayer at gmail.com
Wed Dec 8 12:47:30 EST 2010


Shouldn't
    return 'xx'
be
    return self['xx'


I don't know why precisely you're using a class as a global namespace,
not that I personally find fault with it. But here are some other
things you can do.

Idea one:
======================================================
class NS(object): """place to put junk"""

ns = NS()

ns.global_var1 = "SPAM and eggs"
ns.global_var2 = "use as you like just prefix with ns."
del ns.global_var  # because I'm fickle
dir(ns)

Idea two:
======================================================
Instead of a class as a global namespace, use a module

ns.py
------
"""My global namespace"""
# do not import anything or make
# classes or run functions here, just a place to have varibles

ns_var = "var defined in ns.py"

ignore = ['__builtins__', '__class__', '__delattr__', '__dict__',
'__doc__', '__file__', '__format__', '__getattribute__', '__hash__',
'__init__', '__name__', '__new__', '__package__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__']

main.py
--------
import ns
import mod1
import mod2
import mod3

ns.main_var = "this is main var"

ns.mod3_var = mod3.mod3_var
ns.mod3_somefunc_var = mod3.somefunc.somefunc_var

mod3.show( "ns.ns_var", ns.ns_var)
mod3.show( "ns.main_var", ns.main_var)
mod3.show( "ns.mod1_var", ns.mod1_var)
mod3.show( "ns.mod2_var", ns.mod2_var)
mod3.show( "ns.somefunc_var", ns.somefunc_var)
mod3.show( "ns.mod3_var", ns.mod3_var)
mod3.show( "ns.mod3_somefunc_var", ns.mod3_somefunc_var)
mod3.show( "dir(ns)", dir(ns))
mod3.list_globals()


mod1.py
-------
import ns

# good usage; var not in mod1 global namespace and value is not copied
# from one namespace to another but just put in it.

ns.mod1_var = "this is text in mod1"

# therefore by doing this your code in mod1 is likely to use
# ns.mod1_var and not just mod1_var -is- not ns.mod1_var


mod2.py
-------
import ns

ns.mod2_var = "text in mod2"


def somefunc():
	# good app globals
	ns.somefunc_var = "make a var not in the global namespace of the
mod2"
	ns.renamed_var = "rename this"

somefunc()



mod3.py
-------
# mod3_var is misleading; because you might use it but mod3.mod3_var
# would not be the same value as the ns.mod3_var
mod3_var = "not assigned to ns from in mod3.py but from main.py"


def somefunc():
	# bad globals
	somefunc.somefunc_var = "make a var not in the global namespace of
the mod3"
	somefunc.renamed_var = "rename this"

somefunc()	# instinate somefunc_var

def show(astring, avalue):
	print astring
	print '   ', str(avalue)

def list_globals():
	print 'ns variable list'
	import ns
	print '   [',
	for item in dir(ns):
		if not item in ns.ignore:
			print "'" + item.strip() + "', ",
	print ']'



More information about the Python-list mailing list