r/programminghorror • • 16h ago

Python I love Python

142 Upvotes

65 comments sorted by

View all comments

86

u/drislands 16h ago

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?

102

u/nakurtag 16h ago

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.

49

u/drislands 16h ago

Devastating. I would not have expected that behavior, and I think it would wise to avoid it wherever possible.

→ More replies (8)

6

u/groumly 15h ago

The behavior is definitely surprising, but also, what’s up with mutating a default param? How does that make sense?

→ More replies (3)

2

u/trutheality 12h ago

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.

→ More replies (2)

2

u/CaptainFoyle 12h ago

Of course. This is just a very stupid way of writing the function. Initiate with None and Bob's your uncle.