I have a situation in which the value of the default argument in a function head is affected by an if-clause within the function body. I am using Python 3.7.3.
function definitions
We have two functions f
and j
. I understand the behavior of the first two function. I don't understand the second function's behavior.
def f(L=[]):
print('f, inside: ', L)
L.append(5)
return L
def j(L=[]):
print('j, before if:', L)
if L == []:
L = []
print('j, after if: ', L)
L.append(5)
return L
function behavior that I understand
Now we call the first function three times:
>>> print('f, return: ', f())
f, inside: []
f, return: [5]
>>> print('f, return: ', f())
f, inside: [5]
f, return: [5, 5]
>>> print('f, return: ', f())
f, inside: [5, 5]
f, return: [5, 5, 5]
The empty list []
is initialized on the first call of the function. When we append 5
to L
then the one instance of the list in the memory is modified. Hence, on the second function call, this modified list is assigned to L
. Sounds reasonable.
function behavior that I don't unterstand
Now, we call the third function (j
) and get:
>>> print('j, return: ', j())
j, before if: []
j, after if: []
j, return: [5]
>>> print('j, return: ', j())
j, before if: []
j, after if: []
j, return: [5]
>>> print('j, return: ', j())
j, before if: []
j, after if: []
j, return: [5]
According to the output, L
is an empty list in the beginning of each call of the function j
. When I remove the if-clause, in the body of function j
the function is equal to function f
and yields the same output. Hence, the if-clause seems to have some side effect. Testing for len(L) == 0
instead of L == []
in j
has the same effect.
related to
My question is related to:
- Stackoverflow Question Python Default Arguments Evaluation
- Stackoverflow Question "Least Astonishment" and the Mutable Default Argument and
- the Python Tutorial Section 4.7.1. (Default Argument Values)
But the answers to these question and the tutorial answer only, what I already know.