Repository navigation
Don't let an inner function read its caller's variables (#925) - #935
Merged
craigbarratt merged 1 commit intoDec 1, 2026
Merged
craigbarratt merged 1 commit into
craigbarratt merged 1 commit into
Conversation
…nents#925) When a def was evaluated, resolve_nonlocals() looked for the outside variables the new function reads in the symbol table of every function on the call stack, and shared the first one it found. Python only looks in the functions the def is written inside. So a function made by make() read the caller's variable when the caller had one with the same name, instead of the module's: the script in custom-components#925 returns "caller" where Python returns "global". Before custom-components#924 only callers with an inner function, class or lambda leaked their variables this way; since custom-components#924 every caller does. resolve_nonlocals() now looks only in the symbol table of the function the def is written in. Class bodies don't count, as in Python: for a method it looks through the class body, and any enclosing class bodies, to the function or module around them. ast_classdef() keeps the list of class bodies being run, so it can tell them apart. That table must hold every outside variable that anything written inside the function reads, and no others, so get_names_set() changes in three ways. The first two are names it missed, which only worked before because of the call-stack search: - a name a nested function declares nonlocal, even if it assigns it, so nonlocal works two or more levels deep; - a name the functions in a class body read, even if the class body assigns it, binds it some other way, or declares it global, since methods don't see a class body's names. The class body's own reads of its names stay the class's. - a nested function's parameters and a comprehension's loop variables belong to them, so they're no longer counted as names read from outside, also when read as x.attr. Before, a function in the middle shared an outer variable with the same name, which eval() and locals() there showed. A comprehension's first iterable is still read outside it, and a loop target such as items[i] or obj.attr still reads items, i and obj. Lambdas, comprehensions and generator expressions already looked only in the function they're in, so they now also read the right variable when that function is inside another one. Code run by eval() and exec() no longer picks up the calling function's variables in a def either, as in Python. A new test compares 66 scripts with CPython, each as written and with an inner function: the script from custom-components#925 and the lambda variant from its discussion, the other ways a caller's variable leaked (defs, lambdas, comprehensions and generator expressions two levels deep, methods, a decorator, recursion, eval(), a parameter hiding a built-in, a name only the caller has, a global declaration in the middle function, a trigger decorator, parameters and comprehension loop variables of nested functions), and controls that must keep working: closures called later or after their function returned, nonlocal one and two levels deep, classes whose bodies bind or declare global a name their methods read, their methods' own parameters and comprehension loop variables, comprehension loop targets that assign to a subscript or attribute, and global, del, except ... as, decorators, eval() and exec() at various levels. Defining a function no longer copies and searches the call stack for each name it reads, so it's faster deep in a call chain. Fixes custom-components#925. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
Member
|
Thanks @HoneyBearTech, nice work. The pre-existing differences in your note are fine as follow-ups, after the next release. Merging. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #925.
What was wrong
An inner function could read a variable from whichever function called the function it was made in, instead of the variable Python would use. This is the script from #925:
It gave no error, just the wrong value. The same happened to a function two levels deep, a method of a class made in
make(), a decorator's wrapper, a function made bymake()called througheval(), and a lambda, comprehension or generator expression in a function insidemake(). A caller's parameter could also hide a built-in (def caller(len)maderead()return the caller'slen), and a name that only the caller had was found instead of raisingNameError.Why
defis evaluated,EvalFunc.resolve_nonlocals()decides which outside variables the new function shares. It searched the symbol tables of every function on the call stack (sym_table_stack) and took the first one that kept the name in anEvalLocalVar. Python only looks in the functions thedefis written inside.EvalLocalVars, so only those callers leaked. On 933e177, the script above also gives"caller"ifcallercontains a lambda (the variant from the discussion on Closure captures a caller’s argument after #924 #925). Since Use the new comprehension scoping in every function (#919 follow-up) #924, every function keeps them, so any caller leaks.What I changed
resolve_nonlocals()now looks only in the symbol table of the function thedefis written in, through a newAstEval.enclosing_sym_table(). As in Python, class bodies don't count: for a method, it looks through the class body, and any class bodies around it, to the function or module they're in.ast_classdef()keeps a list of the class bodies being run (class_sym_tables), so it can tell them apart from functions.deflooks. It should also share no others.get_names_set()changes in three ways. It missed two kinds of names, which only worked before because the call stack search found them in the outer function:nonlocalin a nested function. A name a nested function declaresnonlocaland assigns was counted as its own, so the function in the middle didn't share it. It's now counted as needed from outside, sononlocalworks two or more levels deep.Class bodies. A name a class body binds (by assignment,
for,with ... as,import,except ... as,def, a nestedclass, ordel), or declaresglobal, hid the same name that its methods read. Methods don't see a class body's names in Python, so they now read the variable of the function around the class:This already gave
"outer"on master, only because the call stack search foundouter'sx; with the first change alone it would give"global".get_names_set()now collects the names the functions and classes in a class body read separately (inner_free), so the class body's names don't hide them. The class body's own reads of its names stay the class's.Parameters and comprehension loop variables. The other way round, a nested function's parameters and a comprehension's loop variables were counted as names read from outside, also when read as
x.attr. So a function in the middle shared an outer variable with the same name, andeval("x")andlocals()in it showed that variable, where Python doesn't:Through a middle function this was already wrong on master. With the class change above it would also have reached through class bodies, so a method's parameter would have made the function around the class share the outer variable. A nested function's parameters are now its own names (
param_names(), formerlylambda_param_names()), and a comprehension's loop variables are its own. As in Python, its first iterable is still read where the comprehension is, its later iterables, conditions and element can read its loop variables, a:=in it binds in the function around it, and a loop target that assigns to a subscript or attribute (for items[i] in ...,for obj.attr in ...) still readsitems,iandobjfrom outside (get_loop_target_names()). A name read asx.attris checked asx.eval()andexec()no longer picks up the calling function's variables in adefeither. That's what Python does too.eval.pygets 90 new lines and loses 25. 70 of the new lines are code; the rest are comments, docstrings and blank lines.Testing
New
test_closure_scopes_match_pythonrunsCLOSURE_SCOPE_TESTS, 66 scripts, each as written and withwith_inner_function()(132 in all), and compares them with CPython:make(), and of a class in a class;make()called from a class body in the caller, recursively, througheval(), and from the caller's caller; a decorator's wrapper; a caller's parameter namedlen; a name only the caller has, one and two levels deep; the caller's own local variable; a lambda, comprehension and generator expression in a function insidemake(), and a lambda two callers down; aglobaldeclaration in the middle function, which master skipped to read the outer function's variable; a method's inner function reading a name the class body assigns; a function with a@time_triggerdecorator; andeval("x")andlocals()in a middle function whose nested functions have every kind of parameter (positional-only,*args, keyword-only,**kwargs, a lambda's), read directly, asx.realor by an inner function, or whose comprehensions and generator expressions usexas a loop variable (with[y for y in y]reading the outeryin its first iterable);nonlocalone and two levels deep, from a function returned and called later with+=, and from methods of a class and of a class in a class; a parameter of the middle function hiding the name; 18 classes inside a function whose body assigns, binds in another way or declaresglobalthe name their methods read, including a decorator's wrapper, nested classes, a comprehension, generator expression and lambda in the method,@event_triggerand@state_triggermethods,@property,@classmethodand@staticmethod, and methods defined underifandwhile; the same for every kind of method parameter and for comprehension loop variables in methods, checked witheval("x")andlocals()in the function around the class; comprehension loop targets that assign to a subscript or attribute (for items[index] in ...,for (a, items[index + 1]) in ...,for i, items[i] in ...,for obj.attr in ...), in list, set and dict comprehensions and generator expressions, in a laterforclause and in a nested comprehension, in the middle function, a nested function and a method;globaldeclarations at two other levels;delof a shared variable;except ... as; decorators defined in and applied in the middle function, withfunctools.wraps; andeval()andexec().On master,
test_closure_scopes_match_pythonfails, as it should: the 48 runs above differ and the other 84 pass. With this PR, all 132 pass. Each part of the change is needed: without the class change, 19 scripts fail; without thenonlocalchange, 5; without the parameter change, 2; without the comprehension change, 2; without reading a loop target's container, index and object, 2; and without checkingx.attrasx, 1.Looking for code that works on master but not with this PR, I compared many more scripts with CPython, on master and with this PR, each as written and with an inner function. They include comprehensions covering every part of one (each
forclause's target and iterable, conditions, element, key and value, nested comprehensions,:=and lambdas), each put directly in a middle function, in a function inside it, and in a method of a class whose body assigns the same names. With this PR, every one that matches Python on master still does. Comprehensions withasync foraren't supported (on master either), andawaitin a comprehension gives the same results as on master. The ones that matter are in the test above; the others coveredasync def(which can't be compared with CPython directly here),try/finally,with ... as,import ... as,:=, starred assignment, annotations, mutual recursion of inner functions, loop closures,super()in a method's inner function, a class decorator, andeval()in a class body.The full test suite (336 tests), ruff, ruff format, codespell, check json, yamllint, pylint and mypy pass on Python 3.14.
Speed. Each workload is a pyscript function
f(n), run in one process with master'seval.pyand this PR's loaded side by side. Each version gets one warm-up call, then 31 timed calls per workload, alternating the order. The numbers are the best process CPU time of the 31 on Python 3.14. Earlier runs gave the same picture (-15.2% and -16.5% at call depth 100, +1.5% and +1.9% at depth 1, and +2.7% and +3.6% for the method in nested classes).The inner function reads
len,strand the loop variable. On master, each name that isn't in the calling function's own table made a copy of the call stack and searched it, so defining a function got slower the deeper it was called. Now it looks at one table, or a few when thedefis in a class body. Collecting the names a nested function or class reads costs a little more than before (its parameters and comprehension loop variables, and a class body's names kept apart), which shows as about 2 to 4% when defining a function near the top of the call stack or a method in nested classes. Calls and recursion don't define functions, so they're unchanged; their changes here are within run-to-run noise (about 1.5% either way).Docs
No change. The reference doesn't describe the old behaviour, and this restores Python's.
Note
These differences from Python were already there before this PR (master gives the same results), and it doesn't change them:
x = "make"inmake(), anddef inner(a=x)insidemid()insidemake(), the default is"make"in Python. Here,mid()raisesNameErrorif there's no module-levelx, and if there is one, the default is silently the module'sx.get_names_set()doesn't look at default values, base classes or keywords of a nesteddeforclass, somid()doesn't sharex. The same happens with a lambda as a default value (def read(a=lambda: x)gives the module'sx), and with a lambda in a class's base list (class C((lambda: type(x, (), {}))())).def f(): x = "f"followed byclass C: y = x, the class body raisesNameError(or reads the module'sx), where Python gives"f". Two related cases: a lambda in a class body that assigns the same name (x = "class"andread = lambda self: x) reads the module'sxinstead of the function's, andnonlocal xin a class body doesn't change the function'sx.r = mid()followed bylate = "late"andr()inf(), wheremid()returns a function that readslate, raisesNameErrorwhere Python gives"late".I've kept these out of this PR, since each needs its own change, but I'm happy to look at them next.
This PR is one commit on master as of 148e2d3, and it merges cleanly with the current master.