Repository navigation
Let lambdas use the enclosing function's variables (#725) - #919
Conversation
5581080 to
cddf148
Compare
craigbarratt
left a comment
There was a problem hiding this comment.
Thanks @HoneyBearTech, this fixes a common problem: lambdas using a function's variables, e.g. sorted(ids, key=lambda i: data[i]), or self in a method. Approving, with one request: loop_scope.keep_writes() in genexp_loop isn't covered by the tests. Removing it doesn't fail any, and a walrus in a generator expression run by a later comprehension that reuses the name still works without it. Could you add a test that needs it, or drop it if it isn't needed?
A possible follow-up: the new comprehension scoping only applies in functions with an inner function or lambda, so the same code can behave differently depending on that. It would be good to use it in every function eventually.
…#725) A lambda inside a pyscript function could only see globals, so code like sorted(ids, key=lambda i: data[i]) or filter(lambda v: v > limit, items) failed with NameError, and a default such as lambda v=x: v could get an internal EvalLocalVar instead of the value of x. A function's shared local variables now keep their values in Python cells. The lambda is still compiled to a native function, and its free variables are bound to those cells, so it reads their current values each time it's called, as in Python. Defaults are evaluated in the enclosing scope and are plain values. The compiled code is cached per lambda. In a function that shares its variables with an inner function or lambda, comprehension and generator expression loop variables get their own local for each run, so a lambda made in one shares its loop variable as in Python, and they no longer overwrite a function variable with the same name; a generator expression used by a comprehension that started after it was made sees and assigns its own enclosing variables, not the comprehension's loop variables. Other functions handle comprehensions as before. At the end of an except block, its name is unbound like del, so a lambda or inner function sharing it sees that too, and annotated assignments make local variables. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
In a function that shares its variables, every name the function binds already has its EvalLocalVar from the call, and an assignment in a generator expression's element (eg, with :=) only sets that variable's value. Nested comprehensions and generator expressions always put back the bindings they replace, so keep_writes() never found a change to keep. Add GENEXP_WALRUS_SCOPE_TESTS, run by test_genexp_walrus_scopes_match_python: 15 scripts with := in a generator expression run by a later comprehension that reuses the name, compared with CPython. They pass with and without keep_writes(). Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
cddf148 to
30defb9
Compare
|
Thanks @craigbarratt, for the review and for spotting that.
Here's why it's never needed. In a function that shares its variables, every name the function binds (including What changed, in a second commit on top of the original one so you can see it on its own:
I've also rebased the PR on master after #923. The only clash was the tests both PRs add at the end of The follow-up: thanks, I agree it's worth doing. The same cases, which I checked by hand in functions without an inner function, show the difference you describe. In a function without an inner function or lambda, a generator expression run by a comprehension sees the comprehension's loop variable, and a def f():
x = 0
g = ((x := x + 1) for _ in range(3))
r = [x for x in g]
return r, x # pyscript: ([1, 2, 3], 0) Python: ([1, 2, 3], 3)
def f():
g = ((x := i) for i in range(3))
r = [x for x in g]
return x # pyscript: NameError Python: 2
def f():
x = 0
g = ((x := x + 1) + sum([x for x in range(2)]) for _ in range(3))
return [x for x in g] # pyscript: [2, 4, 6] Python: [2, 3, 4]
def f():
x = 0
g = ((x := x + 1) for _ in range(3))
return [next(g) + x for x in range(10, 12)] # pyscript: [22, 24] Python: [11, 13]
def f():
x = 0
g = ((1 / (2 - x)) + (x := x + 1) for _ in range(5))
return [x for x in g] # pyscript: a list of 5 floats Python: ZeroDivisionErrorAdding a lambda to any of these functions (for example |
…924) * use the new comprehension scoping in every function Since #919, only a function with an inner function, class or lambda kept its variables in shared cells, and only there did a generator expression used by a comprehension see the variables where it was made, as in Python. In other functions it saw the comprehension's loop variables instead, so the same code gave different results depending on whether the function had a lambda; for example, a := in the generator expression was lost. Every function now keeps its local variables in cells, so every function handles comprehensions and generator expressions the same way, and has_closure and check_for_closure() are gone. Code run by eval() and exec(), module level and class bodies are unchanged. As in Python, reading a local variable before it has a value now raises UnboundLocalError in every function, including one that hides a built-in such as len. In a generator expression, the function's variables and an enclosing generator expression's loop variables are free variables, so reading one that has no value there raises NameError, as in Python, while reading one of its own loop variables before it's assigned still raises UnboundLocalError. A comprehension's loop variables are no longer counted as the enclosing function's own variables, unless the function binds them itself, so a comprehension over len doesn't hide the built-in, and one over a global's name no longer makes a later read of the global raise UnboundLocalError. Annotations also work when a function has its own __annotations__ variable. To keep the cost low, EvalLocalVar uses __slots__ and takes its value as an optional positional argument, reading a local variable checks its cell once instead of twice, and a call no longer tests an empty variable for each of the function's own variables, which raised and caught an exception each time and made deep recursion slow. The comprehension and generator expression scripts compared with CPython now also run in functions without an inner function. New ones cover the examples from #919, reading a local variable before it has a value, directly, from a generator expression or as a generator expression's own loop variable, comprehensions whose loop variable has the name of a built-in or global, a function's own __annotations__, and exec() with separate locals. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> * test that a function called from a generator expression resets genexp_id Add three scripts to FUNCTION_LOCALS_TESTS, each compared with CPython as written and with an inner function: - a function called from a generator expression reads its own local before it has a value, and gets UnboundLocalError (fails if call() doesn't reset genexp_id); - a zero-argument super() in a method called from a generator expression uses the method's own first argument (fails if call() doesn't reset genexp_iter); - a call in a generator expression's element doesn't change what the rest of the element sees: a free variable with no value gives NameError, and super() still uses the iterator (fail if call() doesn't restore genexp_id or genexp_iter). Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> --------- Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
Closes #725
What was broken
A lambda inside a pyscript function could only see globals:
The first two failed in any function. The last one needed the function to share its variables with an inner function or lambda (here
show()); without one, it already returned 5.Why
EvalLocalVarobjects, not in Python cells.v=xwas evaluated when the lambda was compiled, without the enclosing function's variables, so in a function that shares its variables it ended up as the internal variable object.What I changed
:=) sets the value of the function's variable and doesn't replace its binding, so nothing needs copying back.exceptblock its name is unbound likedel, so a lambda or inner function sharing it sees that too.Changes since review
tests/test_unit_eval.py, where both PRs add tests; both sets are kept, each with its own test function. The first commit's message is unchanged.LoopScope.keep_writes()and its call ingenexp_loop. I ran each case three ways: in CPython, in this PR withkeep_writes(), and with it removed. I ran them in a function that shares its variables (the committed tests below) and also, by hand, without an inner function or lambda, for the cases that don't need one (all but the four that use a lambda ornonlocalinner function). All of them give the same result with and withoutkeep_writes(), and with a check that fails wheneverkeep_writes()changes anything, the full test suite and every case still pass. The cases without an inner function or lambda aren't committed tests, because all but theglobalone still differ from Python, with and withoutkeep_writes()(see the Note). In a function that shares its variables, every name the function binds already has itsEvalLocalVarwhen the function is called, and nested comprehensions and generator expressions always put back the bindings they replace, so there was never a change for it to keep. The cases that match CPython are now tests (see below).Testing
test_lambdas_match_pythonintests/test_unit_eval.py. It runs 50 scripts in CPython and in pyscript and compares every result. They cover lambdas reading parameters and variables of the function they're in and of outer functions, seeing later changes to a variable, defaults, lambdas made in loops, comprehensions and generator expressions,sorted,max,mapandfilterkeys, walrus anddel,exceptnames, and error cases. Two of them checksuper()from Support super(), Base.__init__ and inherited __init__ in pyscript classes (#891) #916 in methods that share their variables with a lambda:super(Cls, self)in lambdas,super()in a lambda's default, andsuper()in comprehensions, generator expressions and inner functions. Three check lambdas in the@propertyand@classmethodmethods from Support @property and @classmethod on pyscript class methods #918: lambdas returned from a getter, setter, deleter or classmethod that use the method's variables (includingcls) and see later changes to them; lambdas made in comprehensions and generator expressions in those methods, reusing loop names (includingcls); and lambdas used as property getters and setters (property(lambda self: ...)) that use the variables of the function they're made in.test_comprehension_scopes_match_python. It runs 29 scripts compared with CPython: 11 comprehension scope scripts, run as written and again with an inner function added so the function shares its variables, plus 7 scripts that only apply when variables are shared (also run with the inner function). They cover loop variables that don't overwrite function variables, generator expressions used by comprehensions that reuse their names, nested and delayed generator expressions, walrus targets, and a comprehension that raises. (Lambdas made in comprehensions and generator expressions are inLAMBDA_TESTSabove.)test_genexp_walrus_scopes_match_python. It runs 15 scripts (GENEXP_WALRUS_SCOPE_TESTS) compared with CPython, each with an inner function added so the function shares its variables. In 14 of them, a generator expression's element has a:=and is run by a later comprehension whose loop variable has the same name. They cover a name with no value yet, a name deleted and assigned again, a lambda reading the name, a lambda made in the element, a:=in a lambda's default, nested comprehensions and generator expressions that reuse the name, several elements (two loops, two generator expressions read throughzip, andnext()in a comprehension), an element that raises before or after its:=, and aglobalname. The 15th has no:=: the element calls an inner function that assigns the name withnonlocal, then one that deletes it, while a comprehension with that loop name runs the generator expression. They pass with and withoutkeep_writes().sphinx-build -Wpass on Python 3.14.Docs
docs/reference.rst: a short paragraph with two examples saying a lambda can use the function's parameters and variables, and those of the functions it's in, and reads their current values each time it's called.Note
Known differences from Python that I didn't fix:
__qualname__of a lambda made inside a function is'<lambda>', where Python gives'f.<locals>.<lambda>'.:=to that name is lost. For example,x = 0; g = ((x := x + 1) for _ in range(3)); r = [x for x in g]leavesxat 0 in such a function, where Python gives 3. With an inner function or lambda in the function, it gives 3 as in Python. I checked this and the other cases without an inner function by hand; they aren't committed tests, because they still differ from Python. This was already the case, and fixing it means using the new scoping in every function, which I'd leave for a separate PR.nonlocalorglobalcan still change the outer variable where Python keeps it. This was already the case.x = property(lambda self: n)written in such a class body raisesNameErrorfornwhen the property is read. This was already the case, for any use of those variables in a class body, not only lambdas.lambda: self.prop) gets a coroutine, since the lambda runs as native code. That's the existing documented limit for native code reading a pyscript property.super()without arguments doesn't work in a lambda (Python finds the lambda's first argument);super(Cls, self)does.__debug__and also binds a name (with:=or in a comprehension) in a nested function can make the enclosing function import an outer variable of that name. It's only visible througheval()orlocals().This PR is rebased on master after #923. It and my
StopIterationPR (#920) both changeeval.py, so they still clash with each other. Whichever merges second needs a rebase, about 6 hunks, inast_lambda,try_handlers,loopvar_scope_saveand the list, dict and set comprehension loops. I'm happy to do it. Both PRs also add tests at the end oftests/test_unit_eval.py, which is a small "keep both" conflict.