Empty list as default parameter

Peter Otten __peter__ at web.de
Fri Nov 21 19:22:11 EST 2003


Alex Panayotopoulos wrote:

> On Fri, 21 Nov 2003, Peter Otten wrote:
> 
> [...]
>> To be consistent you could do
>> 
>> self.myList = myList[:] or []
> 
> TypeError. You can't slice None.
> If you're going to be taking copies on entry, you might as well use
> 
> def __init__( self, myList=[] ):
> self.myList = myList[:]

That was the the idea; if you are copying anyway, the [] default value does
no harm. Shame on me for not making this clear :-(

> However, copying is inefficient. Not a problem in most cases, but
> I've got a lot of objects to initialise. (This is for a GA). Solution: use
> "myList or []", but carefully.

If you are mutating the myList attribute, the changes propagate to the list
given as a parameter only if that parameter was a non-empty list. Such a
behaviour will probably puzzle anyone but yourself (and yourself in a few
months), and what was gained by the shorter expression will be wasted on
documentation and/or debugging. Personally, I would avoid it even in
throwaway scripts.

Peter





More information about the Python-list mailing list