
Why are default arguments evaluated at definition time in Python?
1 Expert Answer

Hayward B. answered 07/31/20
python developer, software enginneer
The issue is this.
It's too expensive to evaluate a function as an initializer every time the function is called.
-
0
is a simple literal. Evaluate it once, use it forever. -
int
is a function (like list) that would have to be evaluated each time it's required as an initializer.
The construct []
is literal, like 0
, that means "this exact object".
The problem is that some people hope that it to means list
as in "evaluate this function for me, please, to get the object that is the initializer".
It would be a crushing burden to add the necessary if
statement to do this evaluation all the time. It's better to take all arguments as literals and not do any additional function evaluation as part of trying to do a function evaluation.
Also, more fundamentally, it's technically impossible to implement argument defaults as function evaluations.
Consider, for a moment the recursive horror of this kind of circularity. Let's say that instead of default values being literals, we allow them to be functions which are evaluated each time a parameter's default values are required.
[This would parallel the way collections.defaultdict
works.]
What is the value of another_func()
? To get the default for b
, it must evaluate aFunc
, which requires an eval of another_func
. Oops.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Steven F.
02/06/20