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

Erik Max Francis max at alcyone.com
Sat Aug 17 19:59:29 CEST 2002


lion wrote:

> 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].

No, L is the name of the formal parameter in the function, not some
global.  What we're talking about implicitly is the case where f is
called with only one argument; that is, where the default argument is
used for the second argument.  (In the first case, the default argument
is a mutable object; in the second it is None.)

In the first example, if you call f with only one argument, the default
argument will be the _same object_ for each invocation, and so same list
will be appended to each time.  This is, in almost all cases, not the
intended behavior.

In the second example, if called with only one argument, f will create a
new list each time, just the same as

	def g():
	    someList = []
	    return someList

will return a unique list each time it is called.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list