Skip to content

Don't let an inner function read its caller's variables (#925) - #935

Merged
craigbarratt merged 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-closure-caller-scope
Dec 1, 2026
Merged

craigbarratt merged 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-closure-caller-scope

Conversation

@HoneyBearTech

@HoneyBearTech HoneyBearTech commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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:

label = "global"

def make():
    def read():
        return label
    return read

def caller(label):
    return make()

read_label = caller("caller")
result = read_label()    # before: "caller"   Python: "global"

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 by make() called through eval(), and a lambda, comprehension or generator expression in a function inside make(). A caller's parameter could also hide a built-in (def caller(len) made read() return the caller's len), and a name that only the caller had was found instead of raising NameError.

Why

What I changed

  • resolve_nonlocals() now looks only in the symbol table of the function the def is written in, through a new AstEval.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.
  • That only works if each function shares every outside variable that anything written inside it reads, since its own table is now the only place a nested def looks. 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:
    • nonlocal in a nested function. A name a nested function declares nonlocal and assigns was counted as its own, so the function in the middle didn't share it. It's now counted as needed from outside, so nonlocal works two or more levels deep.

    • Class bodies. A name a class body binds (by assignment, for, with ... as, import, except ... as, def, a nested class, or del), or declares global, 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:

      x = "global"
      def outer():
          x = "outer"
          def mid():
              class C:
                  x = "class"
                  def read(self):
                      return x
              return C().read()
          return mid()
      result = outer()    # Python: "outer"

      This already gave "outer" on master, only because the call stack search found outer's x; 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, and eval("x") and locals() in it showed that variable, where Python doesn't:

      x = "global"
      def outer():
          x = "outer"
          def mid():
              def m(x):
                  return x
              squares = [x * x for x in range(3)]
              return eval("x")
          return mid()
      result = outer()    # before: "outer"   Python: "global"

      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(), formerly lambda_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 reads items, i and obj from outside (get_loop_target_names()). A name read as x.attr is checked as x.

  • Code run by eval() and exec() no longer picks up the calling function's variables in a def either. That's what Python does too.
  • Defining a function no longer copies the call stack for each name it reads, so it's faster deep in a call chain (see the timing below).
  • Size: eval.py gets 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_python runs CLOSURE_SCOPE_TESTS, 66 scripts, each as written and with with_inner_function() (132 in all), and compares them with CPython:

    • 24 that give a different result on master in both forms: the script from Closure captures a caller’s argument after #924 #925 and its lambda variant; a function two levels deep; a method of a class made in make(), and of a class in a class; make() called from a class body in the caller, recursively, through eval(), and from the caller's caller; a decorator's wrapper; a caller's parameter named len; 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 inside make(), and a lambda two callers down; a global declaration 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_trigger decorator; and eval("x") and locals() in a middle function whose nested functions have every kind of parameter (positional-only, *args, keyword-only, **kwargs, a lambda's), read directly, as x.real or by an inner function, or whose comprehensions and generator expressions use x as a loop variable (with [y for y in y] reading the outer y in its first iterable);
    • 42 controls that already match on master and must keep matching: a function's own variable when the caller has the same name; a class variable with the same name; recursion with its own variable; closures called later, from a different caller, or after their function has returned; nonlocal one 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 declares global the name their methods read, including a decorator's wrapper, nested classes, a comprehension, generator expression and lambda in the method, @event_trigger and @state_trigger methods, @property, @classmethod and @staticmethod, and methods defined under if and while; the same for every kind of method parameter and for comprehension loop variables in methods, checked with eval("x") and locals() 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 later for clause and in a nested comprehension, in the middle function, a nested function and a method; global declarations at two other levels; del of a shared variable; except ... as; decorators defined in and applied in the middle function, with functools.wraps; and eval() and exec().
  • On master, test_closure_scopes_match_python fails, 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 the nonlocal change, 5; without the parameter change, 2; without the comprehension change, 2; without reading a loop target's container, index and object, 2; and without checking x.attr as x, 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 for clause'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 with async for aren't supported (on master either), and await in a comprehension gives the same results as on master. The ones that matter are in the test above; the others covered async 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, and eval() 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's eval.py and 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).

    workload master this PR change
    define an inner function 2,000 times, call depth 1 93.9 ms 95.6 ms +1.8%
    define an inner function 2,000 times, call depth 10 97.0 ms 96.0 ms -1.0%
    define an inner function 2,000 times, call depth 100 118.5 ms 99.9 ms -15.7%
    define a method in a class in a class, 1,000 times 95.1 ms 98.8 ms +3.9%
    calls to a small function (10,000 calls) 318.8 ms 323.2 ms +1.4%
    recursion, 300 levels, 10 locals 32.2 ms 32.4 ms +0.6%
    recursion, 900 levels, 1 local 36.3 ms 36.9 ms +1.4%

    The inner function reads len, str and 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 the def is 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:

  • A default value of a function defined inside another inner function doesn't see the outer function's variables. With x = "make" in make(), and def inner(a=x) inside mid() inside make(), the default is "make" in Python. Here, mid() raises NameError if there's no module-level x, and if there is one, the default is silently the module's x. get_names_set() doesn't look at default values, base classes or keywords of a nested def or class, so mid() doesn't share x. The same happens with a lambda as a default value (def read(a=lambda: x) gives the module's x), and with a lambda in a class's base list (class C((lambda: type(x, (), {}))())).
  • A class body inside a function can't read that function's variables: in def f(): x = "f" followed by class C: y = x, the class body raises NameError (or reads the module's x), where Python gives "f". Two related cases: a lambda in a class body that assigns the same name (x = "class" and read = lambda self: x) reads the module's x instead of the function's, and nonlocal x in a class body doesn't change the function's x.
  • An inner function made by a middle function doesn't see a variable of the outer function that has no value yet when the middle function is called, even if it has one by the time the inner function runs. For example, r = mid() followed by late = "late" and r() in f(), where mid() returns a function that reads late, raises NameError where 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.

…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>
@craigbarratt

Copy link
Copy Markdown
Member

Thanks @HoneyBearTech, nice work. The pre-existing differences in your note are fine as follow-ups, after the next release. Merging.

@craigbarratt
craigbarratt merged commit 409c3a8 into custom-components:master Dec 1, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Closure captures a caller’s argument after #924

2 participants