Empty list as default parameter

Peter Otten __peter__ at web.de
Fri Nov 21 12:38:25 EST 2003


anton muhin wrote:

> Alex Panayotopoulos wrote:
> 
>> On Fri, 21 Nov 2003, anton muhin wrote:
>> 
>> 
>> Was there any reason that this sort of behaviour was not implemented?
>> 
>> 
> It was discussed several times (search for it, if you're interested),
> but I don't remeber details.
> 
>>>Mutable defaults are better avoided (except for some variants of memo
>>>pattern). Standard trick is:
>>>
>>>    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!)
>> 
> 
> if you wish a one-linear, somehting like this might work:
> self.myList = myList or []

This is dangerous, don't do it.

>>> None or "just a marker"
'just a marker'

seems to work. But:

>>> [] or "just a marker"
'just a marker'

I. e. your one-liner will create a new list when the myList argument is not
provided or is provided and bound to an empty list.

Peter




More information about the Python-list mailing list