where dos the default agument live in? local name spaces or gloabal namespaces or else?

lion dance_code at hotmail.com
Sat Aug 17 14:38:51 CEST 2002


Erik Max Francis <max at alcyone.com> wrote in message news:<3D5D8153.BDBB4213 at alcyone.com>...
>Erik Max Francis wrote:
 Usually a better pattern for otherwise-mutable defaults is something
> like:
> 
> 	def f(l=None):
> 	    if l is None:
> 	        l = [] # this will make a new list each time
> 	    ...

These are two functions ,as are well known ,one has the side effect
that L is updated with each call to f,the other has not the bug:
> > has side effect:
> > >>>def f(a, L=[]):
> >         L.append(a)
> >         return L
> > 
> > don't have side effect:
> > >>> def f(a,L=None):
> >         if L is None: L=[]
> >         L.append(a)
> >         return L

I don't know why "L is created on each call  with the second
function.". Let us assume variable "a"  holds the value 1, and once we
invoke the two functions the firt time using  f(a), both L in the two
functins will be updated to [1] as the result of the functions;When we
invoke the two function second time using f(a) , (note that L has
holds the value [1] in both functions), in the first function L is
directly updated to [1,1] , and in the second function ,L is compared
with None, because L holds the value [1] , they don't match, and L
won't be assigned with the value [], so in the end L is also updated
to [1,1].
I  know there must be something wrong with what is explained upside
,but I don't know why.

Regards,
lion



More information about the Python-list mailing list