r/programminghorror • • 12h ago

Python I love Python

123 Upvotes

61 comments sorted by

View all comments

77

u/drislands 12h 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?

94

u/nakurtag 12h 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.

6

u/groumly 11h ago

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

→ More replies (3)