is it a bug ??

Max M maxm at mxm.dk
Wed Jan 29 17:34:36 EST 2003


brauner joel wrote:

> but the same function with the use of the "append" methods :
> 
> def f(a=[]):
>     print a
>     if len(a)<5:
>         a.append(1)
>         f(a)
>     print a
> 
> returns :


It IS confusing. But it *is* documented in chapter 4 of the tutorial.

"
4.7.1 Default Argument Values


Important warning: The default value is evaluated only once. This makes 
a difference when the default is a mutable object such as a list or 
dictionary. For example, the following function accumulates the 
arguments passed to it on subsequent calls:


def f(a, L=[]):
     L.append(a)
     return L

print f(1)
print f(2)
print f(3)

This will print


[1]
[1, 2]
[1, 2, 3]

If you don't want the default to be shared between subsequent calls, you 
can write the function like this instead:


def f(a, L=None):
     if L is None:
         L = []
     L.append(a)
     return L
"


-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list