Empty list as default parameter
Alex Panayotopoulos
A.Panayotopoulos at sms.ed.ac.uk
Fri Nov 21 08:26:13 EST 2003
On Fri, 21 Nov 2003, anton muhin wrote:
> Really common mistake: lists are _mutable_ objects and self.myList
> references the same object as the default parameter. Therefore
> a.myList.append modifies default value as well.
It does?!
Ah, I've found it: listHolder.__init__.func_defaults
Hmm... this behaviour is *very* counter-intuitive. I expect that if I were
to define a default to an explicit object...
def process_tree1( start=rootNode )
...then I should indeed be able to process rootNode through manipulating
start. However, if I define a default as a new instance of an object...
def process_tree2( myTree=tree() )
...then the function should, IMHO, create a new object every time it is
entered. (By having func_defaults point to tree.__init__, or summat.)
Was there any reason that this sort of behaviour was not implemented?
> 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!)
--
<<<Alexspudros Potatopoulos>>>
Defender of Spudkind
More information about the Python-list
mailing list