Empty list as default parameter

Peter Otten __peter__ at web.de
Fri Nov 21 18:56:18 CET 2003


Fredrik Lundh wrote:

> or perhaps:
> 
>     def __init__( self, myList=None):
>         self.myList = myList or []
 

This treats empty and non-empty myList args differently:

>>> mylist = []
>>> (mylist or []) is mylist
False
>>> mylist = [1]
>>> (mylist or []) is mylist
True

To be consistent you could do

self.myList = myList[:] or []

>>> mylist = []
>>> (mylist[:] or []) is mylist
False
>>> mylist = [1]
>>> (mylist[:] or []) is mylist
False

or avoid the above pattern altogether.

Peter




More information about the Python-list mailing list