Newbie question - default values of a function

Bulba! bulba at bulba.com
Wed Dec 22 17:08:23 EST 2004


OK. Don't laugh.


There's this example from tutorial, showing how default
value is computed once when defining function and shared 
between function 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]
---

(PythonWin 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit
(Intel)] on win32.)


Tried it, it works as expected.

But why the following happens?

>>> def j(a,i=0):
... 	i=i+1 
... 	return (a, i)
... 
>>> 
>>> j(2)
(2, 1)
>>> j(3)
(3, 1)
>>> j(5)
(5, 1)


>From Language Reference:

http://www.python.org/doc/2.3.4/ref/function.html

"Default parameter values are evaluated when the function definition
is executed. This means that the expression is evaluated once, when
the function is defined, and that that same ``pre-computed'' value is
used for each call. This is especially important to understand when a
default parameter is a mutable object, such as a list or a dictionary:
if the function modifies the object (e.g. by appending an item to a
list), the default value is in effect modified. "


Surely the variable i is a mutable object?

OK, again:

>>> def t(a,i=[0]):
... 	i[0]=i[0]+1
... 	return (a, i)
... 
>>> t(1)
(1, [1])
>>> t(3)
(3, [2])
>>> t(5)
(5, [3])

Yes, it works with the list. But why sharing value between calls
pertains some mutable objects and not the other mutable objects? 
I'm stymied.



--
It's a man's life in a Python Programming Association.



More information about the Python-list mailing list