B
Bulba!
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?
.... i=i+1
.... return (a, i)
.... (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:
.... return (a, i)
....
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.
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?
.... i=i+1
.... return (a, i)
.... (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:
.... i[0]=i[0]+1def t(a,i=[0]):
.... return (a, i)
....
(5, [3])t(1) (1, [1])
t(3) (3, [2])
t(5)
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.