default value in __init__

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 16 13:23:17 EDT 2008


On Thu, 16 Oct 2008 17:05:40 +1300, Lawrence D'Oliveiro wrote:

> In message <01006451$0$20646$c3e8da3 at news.astraweb.com>, Steven D'Aprano
> wrote:
> 
>> On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote:
>> 
>>> On Oct 9, 10:14 am, Christian Heimes <li... at cheimes.de> wrote:
>>>
>>>> No, it always contains the default argument because default values
>>>> are created just ONE TIME
> <http://effbot.org/pyfaq/why-are-default-values-shared-between-
objects>...
>>> 
>>> 
>>> Wow, it's a very "dangerous" behavior ...
>> 
>> No, it's very *useful* behaviour.
> 
> Can you give an example of how useful it is? Something worth the pain of
> newbies tripping over it every week?


Did you read the effbot's explanation in the link above? He gives two 
examples, memoization and binding of locals.

The second example is especially interesting, because that's also a 
Gotcha for newbies (not just noobs either...), and the solution to that 
specific gotcha is Python's use of define-time binding of default values.


>>> callbacks = [None]*4
>>> for i in xrange(len(callbacks)):
...     callbacks[i] = lambda s: '%d %s' % (i, s)
...
>>> for cb in callbacks:
...     print cb('string')
...
3 string
3 string
3 string
3 string


Newbies get confused by this almost as often as by the default value 
semantics, but the simplest solution to this gotcha is to use Python's 
default values:

>>> for i in xrange(len(callbacks)):
...     callbacks[i] = lambda s, i=i: '%d %s' % (i, s)
...
>>> for cb in callbacks:
...     print cb('string')
...
0 string
1 string
2 string
3 string


If Python re-evaluated the default value i=i at runtime, the above would 
break.



-- 
Steven



More information about the Python-list mailing list