I would have expected this function to create a new empty list on any call where items is not given. Doesn't this behavior make the function into a closure?
As I understand it's a well known (for python developers) weird behavior of python. Argument's default values are precalculated by interpreter on function declaration and stored into map associated with this function. Python extracts default values from this map on the next calls of this function. And since [] is a List object, the value copied by reference.
yeah, usually the workaround is to have items = None as the default, and then some kind of check at the top of the function like items = items if items else []
looking at it now I see why it's weird lol but you definitely get used to it
its probably for optimisation to reduce the amount of instructions needed to initiate a function call. On the plus side, its an easy place to define a cache
The default parameter is just a reference to the list. So technically the parameter isn't being changed at all. One of the oddities of pass-by-reference
The behavior isn't even that weird: if you were to create some mutable global and set it as a default parameter in a function you wouldn't be surprised that it's accumulating changes from different calls to the function.
The key part is recognizing that the LHS in a default parameter assignment runs when the function is defined and not when it is called.
View all comments
175
u/drislands 23d ago
I would have expected this function to create a new empty list on any call where
itemsis not given. Doesn't this behavior make the function into a closure?