Setting a Global Default for class construction?

Erik Max Francis max at
Sat Feb 1 05:14:24 CET 2003

Josh English wrote:

> Here is the code that I am struggling with in a Python module:
> _Thing = "it"
> def SetThing(s):
>         global _Thing
>         _Thing = str(s)
> class NewThing:
>         def __init__(self,thing=_Thing):
>                 self.Thing = _Thing

This binds the default parameter thing to the _current value_ of _Thing,
which is the string 'it'.  Default parameter values are "global" in that
they are not reevaluated after the initial declaration, so that default
parameter will always be that 'it' string.  If you want it to truly be
dependent on the current value of _Thing, try something like:

	def __init__(self, thing=None):
	    if thing is None:
	        thing = _Thing
	    self.Thing = thing

 Erik Max Francis / max at /
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The basis of optimism is sheer terror.
\__/ Oscar Wilde /
 A personal guide to online multiplayer first person shooters.

More information about the Python-list mailing list