Re: evaluated function defaults: stored where?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: evaluated function defaults: stored where?

From: alex23 <wuwei23@gmail.com>
Date: Thu May 26 2005 - 08:14:10 CEST

David Isaac wrote:
> As a Python newbie I found this behavior quite surprising.

It can be even more surprising if a default value is mutable:

>>> def foo(a, b=[]):
... b.append(a)
... return b

>>> foo(3,[1,2])
[1, 2, 3]

>>> foo('c',['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

So far, everything is behaving much as you'd expect, but then:

>>> foo(2)
[1, 2]

>>> foo(3)
[1, 2, 3]

The parameter is bound to the list at creation time and, being mutable,
is modifiable each time the function is called.

This can be avoided by modifying your function slightly:

>>> foo(3, [1,2])
[1, 2, 3]

>>> foo('c', ['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

>>> foo(2)
[2]

>>> foo(3)
[3]

-alex23
Received on Thu Sep 29 16:14:05 2005