pitfall for your amusement

Bengt Richter bokr at oz.net
Tue Nov 12 22:07:47 EST 2002


On Tue, 12 Nov 2002 17:31:14 -0500, mwilson at the-wire.com (Mel Wilson) wrote:

>In article <aqrka3$1emk$1 at nntp6.u.washington.edu>,
>"Russell E. Owen" <owen at nospam.invalid> wrote:
>> [ ... ]
>>If you are collecting pitfalls, here's my least favorite: "never use a
>>mutable object as a default value". A classic example:
>>
>>def badfunc(alist=[]):
>>   ...
>>
>>The default value of alist will not stay [] (an empty list) but instead
>>is affected by whatever you pass in for "alist". Very tricky and
>>unpleasant.
>
>I'm not finding that.  Am I misunderstanding something?  See below ..
>
>        Regards.        Mel.
>
>
>
>Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
>Type "copyright", "credits" or "license" for more information.
>>>> def f2(dflt=[]):
>...     return dflt
>...
>>>> f2()
>[]
>>>> f2(3)
>3
>>>> f2()
>[]
>>>> f2([1,2])
>[1, 2]
>>>> f2()
>[]
>>>>

You're not using it as a mutable. Suppose it's normally a caller's
list, that the function appends some output to, and and empty list
is supposed to be a convenience default to start a new list. Here
the problem is obvious, but with more code it can be more subtle.

 >>> def f3(x, dflt=[]):
 ...     dflt.append(x)
 ...     return dflt
 ...
 >>> f3('a',['something added:'])
 ['something added:', 'a']
 >>> f3('b',['something added:'])
 ['something added:', 'b']
 >>> f3('c')
 ['c']
 >>> f3('d')
 ['c', 'd']


Regards,
Bengt Richter



More information about the Python-list mailing list