+ 2
How do you justify this rather odd behavior of functions working with lists?
4 odpowiedzi
+ 3
In order to always use an empty list if this parameter is not provided, you have to rewrite the function like this:
def f(x,y=None):
if not y:
y = []
In this way the list creation remains in local scope and invoked every time when calling the function.
This is one of the common pitfalls in Python, using a mutable value (list in this case) as default argument.
+ 4
Actually it's all logical.
A function f has an attribute __defaults__. You can access it like any other class attribute.
When you define default args, the values are stored in that defaults tuple *once* when the function is defined.
Whenever you call f and don't pass that argument, the function will store the value from the __defaults__ in there.
And when you put a list as a default argument, it will always be that very same list you're pulling out.
+ 3
Whoa, thx guys, that solved everything. Unfortunately I can't mark all the answers as right, but to me all of you were helpful. Much obliged 🙏🏼🙏🏼 Tibor Santa, HonFu and last but not least Seb TheS
+ 2
The default argument always uses the same value, if you change the value you will always get the modified value when you use the default argument.