pitfall for your amusement

Gonçalo Rodrigues op73418 at mail.telepac.pt
Tue Nov 12 18:30:23 EST 2002


On Tue, 12 Nov 2002 13:30:02 -0800, Erik Max Francis <max at alcyone.com>
wrote:

>"Russell E. Owen" wrote:
>
>> 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.
>> 
>> Here's my usual solution:
>> def okfunc(alist=None):
>>    alist = alist or []
>
>If you're using None as a sentinel value, it's probably better to test
>for None-ness (via alist is None) rather than test for truth, since many
>things can be false which are not None.
>
>It's unlikely that in this particular example it would pose a problem,
>but in the more general case it could.  The idiom _I_ use is:
>
>	def f(l=None):
>	    if l is None:
>	        l = []
>	    ...

And when I want to use None *also* as viable input I use something like

DEFAULTARG = []

def f(l = DEFAULTARG):
    if l is DEFAULTARG:
        <whatever>

With my best regards,
G. Rodrigues



More information about the Python-list mailing list