|
|
|
|
|
by nitroll
2239 days ago
|
|
It does make sense to evaluate the default value for the parameter at the point of definition for serveral reasons.
First of all, the default value does not have to be a literal value, and if you wanted it to be evaluated at call time the function would need to capture all of the default values in a closure. default = 10
def foo(x=default):
return x
default = 20
assert foo() == 10
I think tat makes a lot of sense.It could also be that the default value is a more ocmplex expression, we could use a function to generate a default argument. def foo(x=create_default(y, z))
By evaluating it at definition time we only have to evaluate the expression once and not have this weird lazy expression.And yes it is used, for example the fastapi Dependency Injection system has been build quite cleverly using the ability to construct default values https://fastapi.tiangolo.com/tutorial/query-params-str-valid... Yes it is one of those things you just have to learn, but there are tons of stuff like that in most programming languages. |
|
I don't understand your "closure" comments; either way, things are being lexically closed. It's a question of when evaluation takes place, not in what scope or under what scoping discipline.
In fact, Python's treatment requires the implementation to have a hidden storage that is closed over; the equivalent of my stable_snapshot variable has to be maintained by the implementation. The definition-time evaluation has to stash the value somewhere, so to that it can use that one and not the current.