r/programminghorror • • 29d ago

Python I love Python

303 Upvotes

81 comments sorted by

View all comments

Show parent comments

189

u/nakurtag 29d 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.

8

u/groumly 29d ago

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

7

u/ChemTechGuy 29d ago

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

2

u/groumly 28d ago

That’s not what I meant.

Mutating input is already not a good pattern, but mutating a default param is even worse.

You can’t tell if it was passed or not, so even without the interning oddity, you end up mutating something that nobody but you has access to.

3

u/ChemTechGuy 28d ago

Go complain to Guido van Rossum then, I'm just telling you how it works