Python Forum

Full Version: mutable argument in function definition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
the below code is in :
https://realpython.com/python-mutable-vs...-a-summary


in the below code:
def append_to(item, target=[]):
    target.append(item)
    return target
after running, What you might expect to happen:
append_to(1)
# expected output :[1]
append_to(2)
# expected output :[2]
append_to(3)
# expected output:[3]
On the site is written that:
Quote:Because Python defines the default argument value when it first parses the function and doesn’t overwrite it in every call, you’ll be working with the same instance every time. Then, you don’t get the above output. Instead, you get the following output:
# What actually happens:
append_to(1)
# output is
Output:
[1]
append_to(2
)# output is
Output:
[1,2]
append_to(3)
# output is 
Output:
[1,2,3]
I did not understand what was written there. can explain it to me?
thanks
This is what you are doing:
default_target = []
def append_to(item, target=default_target):
    target.append(item)
    return target
When the module is first imported, a list object is created to serve as the default value for target. I explicitly do that in my example above, but functionally it is the same as what happens in your example. If you want a different list each time the function is called you need to do this:
def append_to(item, target=None):
    return [item] if target is None else target.append(item)
But you should reconsider wanting to do this at all. I'm having a hard time thinking of a use case where I want a default mutable argument that is returned as the value of the function.