bug or feature?

Steve Holden steve at holdenweb.com
Wed Oct 5 07:07:20 EDT 2005


beza1e1 wrote:
> Coming back from a bug hunt, i am not sure what to think of this python
> behaviour. Here is a demo program:
> 
> class A:
>    def __init__(self, lst=[]):
>       self.lst = lst
> 
> a = A()
> b = A()
> b.lst.append("hallo")
> print a.lst # output: ["hallo"]
> 
> 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.
> 
Interestingly I couldn't find this in the FAQ, though it *is* a 
frequently-asked question [note: my not finding it doesn't guarantee 
it's not there]. The nearest I could get was in

 
http://www.python.org/doc/faq/programming.html#my-program-is-too-slow-how-do-i-speed-it-up

which says:

"""Default arguments can be used to determine values once, at compile 
time instead of at run time."""

The point is that the value of the keyword argument is determined when 
the def statement is executed (which is to say when the function body is 
being bound to its name).

If the default argument is (a reference to) a mutable object (such as a 
list instance) then if one call to the function modifies that mutable 
object, subsequent calls see the mutated instance as the default value.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list