is it a bug ??

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Wed Jan 29 22:10:58 CET 2003


brauner joel <jbrauner at wanadoo.fr> writes:
> def f(a=[]):
> 	print a
> 	if len(a)<5:
> 		a.append(1)
> 		f(a)
> 	print a
> 
> returns :
> 
> []
> [1]
> [1, 1]
> [1, 1, 1]
> [1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> [1, 1, 1, 1, 1]
> 
> In other words, the recursive function f seems to make the a list
> global for all the occurences of the function
> 
> is that normal ?

The problem is the default arg [] is evaluated only when f is defined,
not every time it's called.  So whenever you call f, you always get
the exact same list.  Once you've mutated the list, it stays mutated.




More information about the Python-list mailing list