Hacker News new | ask | show | jobs
by yatac42 1952 days ago
> Also, the mutable default arguments problem is quite difficult to solve in any other way. Python never copies things for you.

Why would it need to copy anything? What's wrong with just evaluating the default argument expression every time the function is called with a default argument rather than once at definition-time? That's how it works in other languages.

2 comments

The variables used in the expressions might not be in scope (in fact they usually aren't). Also, I'm rather sure that's how it works in C++ (which by accident copies arguments instead of leaving a reference, but the single time default argument evaluation holds).
> The variables used in the expressions might not be in scope (in fact they usually aren't).

That's solved easily enough by evaluating the expression in the scope where it was defined (again that's what other languages do).

> Also, I'm rather sure that's how it works in C++

Default arguments in C++ work as I described: If you define `void f(int arg = g(x)) {}`, then calling `f()` n times will call `g` n times as well (using the `x` that was in scope when `f` was defined) - and if you never call `f`, `g` isn't called either.

An example demonstrating this: https://ideone.com/vs26Oq

That’s a good idea, I like that!