The default argument is evaluated at call time. So, unlike (for example) Python, a new object is created each time the function is called.
This is something I didn’t know before. I tested it and that’s true.
def test(x, y = ):
So I tried searching why this happens and I got some answers here.
It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the like to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it.
The reason for this is that the def statement only gets executed once, which is when the function is defined. Thus the initializer value only gets created once. For a reference type (as opposed to an immutable type which cannot change) like a list or a dictionary, this ends up as a visible and surprising pitfall, whereas for value types, it goes unnoticed.
Usually, people work around it like this: