
On Sun, Oct 31, 2021 at 02:24:10PM +1100, Chris Angelico wrote:
That last part is the most important here: it has to be evaluated *in the context of the function*. That's the only way for things like "def f(a, n=len(a)):" to be possible.
Agreed so far.
Every piece of code in Python is executed, if it is ever executed, in the context that it was written in.
I don't think that's quite right. We can eval() and exec() source code, ASTs and code objects in any namespace we have access to, including plain old dicts, with some limitations. (E.g. we can't get access to other function's namespace, not even if we have their locals() dict. At least not in CPython.) In the case of default expressions: def func(spam=early_expression, @eggs=late_expression): early_expression is evaluated in the scope surrounding func (it has to be since func doesn't exist yet!) and late_expression needs to be evaluated inside func's scope, rather than the scope it was written in. -- Steve