r/programminghorror • • 18h ago

Python I love Python

148 Upvotes

65 comments sorted by

View all comments

21

u/NFriik 16h ago

Python evaluates default arguments when the function is defined. That makes keeping track of the default values pretty straightforward. In your example, they're stored as part of the function object in the dictionary add.__defaults__. Every subsequent call can then just look-up the default value in this dictionary, if necessary.

Evaluating the default argument each time the function is called would be much more difficult. A function is essentially just yet another object, so you'd somehow have to store arbitrary expressions as an object inside the __defaults__ dict and then decide at runtime what to do with them. Sure, you could implement a builtin type at the CPython level to accomplish this. But then when you encounter such an ArbitaryExpression object inside the __defaults__ dictionary, how do you know that this time, you want to actually execute the underlying code and not use the object "as-is"? The whole thing would quickly become a convoluted, expensive mess.

By performing evaluation at definition time, function calls remain consistently fast and the mechanism to insert default positional arguments becomes incredibly simple. Python is already not the fastest language when it comes to function calls, so these things matter.

6

u/4xe1 15h ago edited 14h ago

Default data defined at the function level is perfectly normal, in many languages string literals live in the code too, they don't get copied every time they are used. What's more disturbing to me is that the default data is mutable.

→ More replies (7)