Repository navigation
Use the new comprehension scoping in every function (#919 follow-up) - #924
Conversation
Since custom-components#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 custom-components#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>
craigbarratt
left a comment
There was a problem hiding this comment.
Thanks @HoneyBearTech, this is a nice result: one rule for every function, and functions with an inner function or lambda get much faster in deep recursion.
I compared about 25 more scripts with CPython, each as written and with an inner function: arguments and defaults, except ... as e unbinding, del, for/with/import targets, locals(), recursion, global, nonlocal, a local hiding print, comprehension variables not leaking, lambdas in comprehensions, nested comprehensions, :=, inner classes and functions. All of them match. I also timed small calls, a local loop, and recursion with 10 locals with and without an inner function at realistic depths, and got within noise of master (the inner-function case a few percent faster).
One small request. Every mutation I tried was caught by the tests except one: if EvalFunc.call() doesn't reset genexp_id, nothing fails. This script catches it (it gives NameError instead of UnboundLocalError), so it would be worth adding to FUNCTION_LOCALS_TESTS:
def h():
try:
y = z
z = 1
except NameError as e:
return type(e).__name__
def f():
return list(h() for _ in range(1))
result = f()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>
|
Thanks @craigbarratt, and thank you for the roughly 25 extra comparisons and the timings. It's good to know that arguments and defaults, What I added. I pushed one new commit on top of the existing one, Your script fails with the reset removed. I took the The other resets. I did the same for each of the other steps in that part of
So I added two small scripts, each checked against CPython and run in both kinds of function:
With these, every removal I tried makes at least one script fail, in both kinds of function: the The full suite (335 tests) and the pre-commit checks pass. Thanks again for catching this. |
craigbarratt
left a comment
There was a problem hiding this comment.
Thanks @HoneyBearTech, the new tests catch every reset and restore. Approving.
This is the follow-up @craigbarratt suggested on #919: "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." With this PR, every function uses it.
What was different
Since #919, a generator expression used by a comprehension behaved as in Python only in a function that has an inner function, class or lambda. In any other function it saw the comprehension's loop variables instead of the variables where it was made, so a
:=in it was lost, or it read the wrong value. Adding an inner function, or a lambda that reads a variable, to the function changed the result, even if it was never called:These are three of the five examples from my reply on #919. All five now match Python in any function.
Why
EvalLocalVarthat holds a Python cell, so an inner function or a lambda can share it.EvalFunc.has_closuremarked those functions, andcheck_for_closure()set it.has_closurewas true (shares_locals()).What I changed
EvalLocalVars:EvalFunc.call()makes one for each of the function's own variables on every call, as it did before only in functions with an inner function.has_closureandcheck_for_closure()are removed, since nothing else used them.shares_locals()keeps its test that a pyscript function is running (self.in_local_scope() and self.curr_func is not None) and only drops thehas_closurepart. Code run byeval()andexec()has no running function and keeps a plain dictionary of variables, so it's unchanged. Turning the new handling on there would break a case that works today: with separate locals,exec('g = ((x := x + 1) for _ in range(3)); r = [x for x in g]', {'x': 0}, ns)would giver == [1, 1, 1]instead of Python's[1, 2, 3].UnboundLocalError("local variable 'x' referenced before assignment") in every function, not only in one with an inner function. Before, it wasNameError("name 'x' is not defined"), or, for a local that hides a built-in, the built-in itself:n = len("ab")followed later bylen = 5gave2instead of raising.UnboundLocalErroris a subclass ofNameError, so code that catchesNameErrorstill works.NameError, notUnboundLocalError. The generator expression's own loop variables are local to it, so reading one before it's assigned ((x for _ in [0] for x in x)) still raisesUnboundLocalError. A list comprehension's loop variables are local to the function or generator expression it runs in, as in Python 3.12 and later. To tell these apart, the new loop variables that comprehensions and generator expressions get are anEvalLoopVar, a small subclass ofEvalLocalVarthat remembers which generator expression they belong to, orNoneoutside one. Each generator expression gets its own identity object (genexp_id), kept with the rest of its scope next togenexp_iterand set while its element, conditions and inner iterables run;genexp_iteritself can't be used, since two generator expressions can share one iterator.ast_name()raisesUnboundLocalErrorfor an emptyEvalLoopVaronly when that generator expression is the one running, and for an empty function variable only when no generator expression is running (a function called from one resetsgenexp_id, as it doesgenexp_iter). This was already wrong on master in some of these cases, in both kinds of function. Lambdas and inner functions that read an empty variable of the function already raisedNameError, as in Python.get_names_set()), unless the function also binds them itself. As in Python, they belong to the comprehension, which already gives them their own variables while it runs. Since every function now has a variable for each of its own names, leaving them counted would have madelenunbound after (or before)[len for len in range(2)], instead of finding the built-in. It also fixes a case that was already wrong on master in every function: with a module-levelx, readingxin a function after[x for x in range(2)]raisedUnboundLocalErrorinstead of reading the global.ast_annassign()now also works when the function has its own__annotations__variable (__annotations__ = {}or__annotations__: dict = {}), which is now anEvalLocalVartoo: it adds the annotation to that variable's dictionary. Before, this only failed in functions with an inner function.EvalLocalVarper local variable, and every read or write goes through it. To keep that cost low, without changing behaviour:EvalLocalVarhas__slots__, and takes its value as an optional positional argument instead of a**kwargsdictionary;ast_name()reads anEvalLocalVar's cell once. Before, it checked that the variable had a value and then read it again withget(). It only checks for an unbound local when the cell is empty, and raises the same errors as before;EvalFunc.call()no longer checks whether the function's own variables have a value.resolve_nonlocals()used to keep an emptyEvalLocalVarfor each of them, andcall()tested it withis_defined(), which raises and catches aValueErroron an empty cell. Raising an exception costs more the deeper the chain of running coroutines, so with every function usingEvalLocalVars, deep recursion would have got much slower (on master this already happens in functions with an inner function). They're now marked withNone, and each call makes a newEvalLocalVarfor them as before; only variables shared from an enclosing function are tested.eval.pygets 61 new lines and loses 46. 44 of the new lines are code, and the rest are 4 docstrings, 8 comment lines and 5 blank lines.Testing
test_comprehension_scopes_match_pythonandtest_genexp_walrus_scopes_match_pythonnow run every script both as written, in a function without an inner function, and withwith_inner_function(), so both kinds of function are covered. Since the two kinds no longer differ, I mergedSHARED_COMPREHENSION_SCOPE_TESTSintoCOMPREHENSION_SCOPE_TESTS. The first test now runs 36 scripts (18 twice) and the second 30 (15 twice), each compared with CPython.New
test_function_locals_match_pythonruns 23 scripts, each as written and withwith_inner_function()(46 in all), and compares them with CPython:ZeroDivisionErrorin Python, so the script catches it and returns it withx;lenbefore it's assigned. Both giveUnboundLocalError, as in Python;del x, and before it's assigned from a generator expression's element, condition and inner iterable. These giveNameError. Also a lambda and an inner function reading it afterdel x(NameError), and a list comprehension (UnboundLocalError);UnboundLocalError); and an outer generator expression's or a list comprehension's loop variable read by an inner generator expression before it's assigned (NameError), also when the inner one uses the outer one's iterator;lencalled before and after a list, set and dict comprehension and a generator expression whose loop variable islen(4 scripts), and a module-levelxread in a function after all four kinds usexas their loop variable;__annotations__, set with__annotations__ = {}beforex: int = 1, and with__annotations__: dict = {};exec()case above, in a function and at module level, which checks that code run byexec()keeps its old handling;UnboundLocalError, andNameErrorifcall()doesn't resetgenexp_id); a method that calls a zero-argumentsuper()when called from one; and an element that calls a function and then reads a variable with no value yet, or usessuper(), which must see the same scope after the call.test_eval_exceptions: the case where an inner function reads a variable that its own laterdel xmakes local now expects Python'sUnboundLocalError, with the same position.On master, 22 of the 27 scripts that only matched Python in a function with an inner function fail when run in one without: 6 of the 7 former
SHARED_COMPREHENSION_SCOPE_TESTS, 11 of the 15GENEXP_WALRUS_SCOPE_TESTS, and all 5 reply examples. The other 5 already passed and stay as checks: one goes througheval(), three already have their own lambda or inner function, and one uses aglobalname. The twoUnboundLocalErrorscripts fail on master too, and so does the module-levelxscript, in both kinds of function. Thelenscripts for list, set and dict comprehensions, both__annotations__scripts and the two generator expressionNameErrorscripts pass on master as written, but fail there with an inner function. The loop variable script fails on master in both kinds of function; the one where the inner generator expression uses the outer one's iterator passes there, and checks that this stays as it is. Theexec()script passes on master, as it should; it fails ifshares_locals()drops its running-function test. All four changed or new tests fail on master.I also checked, on master and with this PR, that
locals(),eval()andexec()in a function, recursion,globalwithdel, a decorator closure withnonlocal,super(), a@pyscript_compileinner function, a@pyscript_executorfunction, tasks made from a generator expression, and releasing a function's variables after it returns (and after a returned generator is closed) give the same results as before. Module-level and class-body cases are unchanged too.Speed. Each workload is a pyscript function
f(n), run in one process with master'seval.pyand the other versions loaded side by side. Each version gets one warm-up call, then 20 timed calls per workload (10 for the last four rows), alternating the order. I ran that in 3 separate processes (with different hash seeds, since the results move a little from one process to the next), on an otherwise idle machine. The numbers are changes in the median process CPU time against master on Python 3.14, as the range over the 3 processes:The recursion workloads are
def r(n)with 1 or 10 local variables besidesn, which callsr(n - 1)untilnis 0, and in the last four rows also defines an inner function. So most of their time is function calls, and each call now makes anEvalLocalVarfor every local variable. That's why deep recursion in a function with 10 local variables is the slowest case: up to about 14% slower than master in these runs. Calls to a small function are up to about 9% slower, and the other workloads are within about 2%.Functions with an inner function or lambda, which already used
EvalLocalVars on master, got much faster in deep recursion: 1.7 to 6.7 times as fast in the last four rows, becausecall()no longer tests each of their empty variables by raising and catching an exception. The gain grows with depth and the number of variables; a separate check at 900 and 1,900 levels with up to 50 local variables measured 3 to 17 times as fast.Without the first two speed-ups above, an earlier version of this change measured the same way was +4.4% to +5.3%, +8.1% to +11.5%, +13.8% to +17.3% and +3.9% to +6.7% on the first four workloads; most of that came from reading each variable twice. In the runs above, keeping the
is_defined()test of the function's own empty variables incall()made the first four recursion workloads +87% to +93%, +231% to +248%, +209% to +223% and +722% to +766%.I also measured a narrower alternative, in case you'd prefer it: keep the old inner-function-or-lambda test and also share the variables of every function that contains a generator expression. It's in the last column, with the same speed-ups; these functions have no generator expression, so they don't share their variables and cost about the same as on master (one recursion row was up to about 6% slower). It fixes the same 27 scripts, but not the two
UnboundLocalErrorcases, and it keeps a rule about which functions are special, which is what this PR removes. Since every function costs at most about 9% more on the first four workloads, and up to about 14% on deep recursion with many local variables, I went with every function.The full test suite (335 tests), ruff, ruff format, codespell, pylint, mypy and
sphinx-build -Wpass on Python 3.14.Docs
In Language Limitations, the item about generator expressions ended with "unless it was made in a function that has an inner function or lambda". It now says that the difference (a generator expression used by a comprehension sees the comprehension's loop variables) remains only at module level and in class bodies.
Note
Left as it is:
x = 7at module level, a class body withg = (x + 1 for _ in range(3))andr = [x for x in g]gives[8, 9, 10], where Python gives[8, 8, 8]. Your suggestion was about functions, so I've kept these out of this PR.eval()andexec()keeps its old handling too, as explained above.These differences from Python were already there before this PR (master gives the same results), and it doesn't change them:
def f()withx = 7,inner = list((x for _ in range(2)) for x in range(3))followed by[list(g) for g in inner]gives[[7, 7], [7, 7], [7, 7]], where Python gives[[2, 2], [2, 2], [2, 2]].global x, a comprehension with the loop variablexoverwrites the globalx(also in Language Limitations). Withx = 0at module level,[x for x in range(3)]in such a function leaves the globalxat2, where Python leaves it at0.:=that rebinds a comprehension's loop variable is accepted:[(x := 1) for x in range(3)]gives[1, 1, 1], where Python raisesSyntaxError: assignment expression cannot rebind comprehension iteration variable 'x'.This PR is two commits on current master (933e177): the change, and a second commit with the tests you asked for in your review.