global variables - how??

Donn Cave donn at u.washington.edu
Wed Apr 12 16:11:25 EDT 2000


Quoth "Anders Eggers-Krag" <aek at mail1.stofanet.dk>:
| how do I define a propper global variable that works in all functions in all
| modules?

A proper global variable is a bigger job in Python than in some other
languages.  You still have to import its home module, in each module
that will use it, and if any but that home module will modify it, the
context must refer to some mutable object.

Here's one way to do it:

#  --- module main.py ---
class Core:
	def __init__(self):
		self.debug = 0

core = Core()

#  --- module spud.py ---
from main import core

def debug(on):
	if core.debug:
		print 'debug', on
	core.debug = on

You could eliminate the class instance and use the module directly,
changing "from main import core" to "import core".  But the class
gives you more flexibility that you may wish for later.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list