简体   繁体   中英

Printing Return Value of Function having Mutable Default Argument

After reading this thread , I also tried to get my hands dirty with default arguments. So, following is the same function having the mutable default argument:-

def foo(x = []):
    x.append(1)
    return x

As defined in the docs , the default value is evaluated only once when the function is defined.
So, upon executing this statement, print(foo(), foo(), foo()) , I expected the output to be like this: [1] [1, 1] [1, 1, 1]

Instead, this is what I actually got as an output:-

>>> print(foo(), foo(), foo())
[1, 1, 1] [1, 1, 1] [1, 1, 1]

The way the statement is executed (according to me) is that the 1st function call returns [1], the 2nd returns [1, 1] and the 3rd function call returns [1, 1, 1] but it's the 3rd function call return value only which is printed repeatedly.

Also, printing the same function return values as separate statements(as mentioned in that thread) gives expected result, ie,

>>> print(foo())
[1]
>>> print(foo())
[1, 1]
>>> print(foo())
[1, 1, 1]

So, why printing the same function return values together doesn't return the output the way it does when executed separately?

What you didn't try in your second example is to save the return references like this:

a = foo()
print(a)
b = foo()
print(b)
c = foo()
print(c)

print(a, b, c)

Output:

[1]
[1, 1]
[1, 1, 1]
[1, 1, 1] [1, 1, 1] [1, 1, 1]

Now you should be able to see that a, b, c actually refer to the same list which has different contents at different times.

the argument L is evaluated only once in the arg line, but by the time print function is executed the list is mutated to [1, 1, 1]. The most simple solution to prevent this is to copy/duplicate the list content each time.

print(foo()[:], foo()[:], foo())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM