[Tutor] Strange namespace issue

Alexandre Ratti alex@gabuzomeu.net
Thu, 04 Apr 2002 18:05:59 +0200


Hello,


At 10:23 04/04/2002 -0500, you wrote:
>Date: Wed, 3 Apr 2002 21:15:29 +0200
>From: Remco Gerlich <scarblac@pino.selwerd.nl>
>Subject: Re: [Tutor] Strange namespace issue

> > ... I expected self.nodeList to be initialised to a new, empty list if the
> > constructor was called without a nodeList argument. Somehow it failed. I
> > had to use "nodeList = None" in the argument list and then to specify
> > "self.nodeList = []" to initialise the list properly.
> >
> > What did I miss? Is this the normal behaviour?
>
>Yes, it is normal. The default argument is evaluated at the moment that 
>the function is defined. So at the moment you define the class, with the
>function definition in it, the expression "[]" is evaluated, and it returns
>a list. This list is then used as the default for the function argument.

Thanks Remco; this issue had been nibbling at me for a couple of days.

>That list! It will always be the same object.

Yes, that's a subtle trick it played on me.

>The FAQ explains this in different words,
>http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp
>
>This bites you once and then you remember it. Don't use mutable default
>arguments. Use None, and a test for "if argument is None: argument=[]" at 
>the top of a function.

I definitively will remember it :-)


Cheers.

Alexandre