bug or feature?
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Wed Oct 5 08:53:11 EDT 2005
On Wed, 05 Oct 2005 03:39:30 -0700, beza1e1 wrote:
> Coming back from a bug hunt, i am not sure what to think of this python
> behaviour.
[snip code]
> The point seems to be, that lst=[] creates a class attribute (correct
> name?), which is shared by all instances of A. So a.lst ist the same
> object as b.lst, despite the fact, that object a is different to object
> b.
Not a bug, but not really a feature as such, it is a side-effect of
the way Python works. I guess that makes it a gotcha.
Argument defaults are set at compile time. You set the argument default to
a mutable object, an empty list. Every time you call the function,
you are appending to the same list.
This is not a problem if your argument default is a string, or a number,
or None, since these are all immutable objects that can't be changed.
I suppose someone might be able to come up with code that deliberately
uses this feature for good use, but in general it is something you want to
avoid. Instead of:
def spam(obj, L=[]):
L.append(obj)
do this:
def spam(obj, L=None):
if L is None: L = []
L.append(obj)
--
Steven.
More information about the Python-list
mailing list