Repost: function/method default-values bug(?)

Kenneth Manheimer (klm@nist.gov)
Tue, 26 Jul 1994 19:22:47 GMT

This is probably the most important of my lost postings, concerning a
flaw in the parameter-defaulting mechanism. The problem exists in
python 1.0.3 (compiled under sunos 4.1.3 using gcc version 2.5.8,
which very likely doesn't matter).

-=- -=- -=-

I have discovered what is probably a bug, or else at least a
distinctly undesirable feature, in the mechanism which assigns the
default values for functions and methods.

The problem is that the default is altered by mutation of variables to
which it has been assigned. For example:

>>> def uhoh(aparam = {}): # Simple func returns the default.
... return aparam
...
>>> testee = uhoh() # Simple call gets the default.
>>> testee
{}
>>> testee['x'] = 1 # Simple assignment to that var.
>>> testee
{'x': 1}
>>> different = uhoh() # New var gets the default
>>> different
{'x': 1} # Oops - ought be {}

Evidently the default value is only evaluated once, when the function
is defined, and that same object is used for all invocations. More
evidence:

>>> zzz = 1
>>> def ahoy(x = zzz): return x
...
>>> zzz = 2
>>> ahoy()
1

The workaround, of course, is to make the default value a distinct,
non-mutable object, and then assign a fresh copy of the desired real
default if the parameter winds up with the non-mutable one. It would
probably be correct to have the default evaluated each time it is
required (and i'd bet that was the intention, though i am sometimes
more confused than i realize).

Ken
ken.manheimer@nist.gov, 301 975-3539