Empty list as default parameter

Andrei project5 at redrival.net
Fri Nov 21 09:39:46 EST 2003


Alex Panayotopoulos wrote on Fri, 21 Nov 2003 13:26:13 +0000:

<snip> 
> Hmm... this behaviour is *very* counter-intuitive. I expect that if I were 
> to define a default to an explicit object...

I think so too. It's documented as a Python pitfall. Here are some more:
http://zephyrfalcon.org/labs/python_pitfalls.html

>>     def __init__(self, myList = None):
>>         if myList is None:
>>             self.myList = []
>>         else:
>>             self.myList = myList
> 
> Thank you. I shall use this in my code. (Although I would have preferred a 
> trick that uses less lines!)

You could use the quasi-ternary trick:

>>> mylist = None
>>> (mylist is None and [[]] or [mylist])[0]
[]
>>> mylist = []
>>> (mylist is None and [[]] or [mylist])[0]
[]
>>> mylist = [3,4]
>>> (mylist is None and [[]] or [mylist])[0]
[3, 4]

Not that big an improvement really :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.






More information about the Python-list mailing list