Skip to content

Let lambdas use the enclosing function's variables (#725) - #919

Merged
craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:fix-lambda-closure-725
Nov 22, 2026
Merged

craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:fix-lambda-closure-725

Conversation

@HoneyBearTech

@HoneyBearTech HoneyBearTech commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Closes #725

What was broken
A lambda inside a pyscript function could only see globals:

def sorted_ids(ids, data):
    return sorted(ids, key=lambda i: data[i])    # NameError: name 'data' is not defined

def above(values, limit):
    return list(filter(lambda v: v > limit, values))    # NameError: name 'limit' is not defined

def default_value():
    x = 5
    def show():
        return x
    f = lambda v=x: v
    return f()                                   # returned an internal EvalLocalVar, not 5

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

  • A lambda is compiled to a native Python function, so it has no way to reach a pyscript function's local variables. Those live in pyscript's own EvalLocalVar objects, not in Python cells.
  • A default such as v=x was 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.
  • Comprehension and generator expression loop variables were stored in the function's own variables. A lambda made in one could not share its loop variable as it does in Python, and the loop variable overwrote a function variable with the same name.

What I changed

  • A function's shared local variables (those used by an inner function or lambda) now keep their values in Python cells.
    • The lambda is still compiled to a native function. Its free variables are bound to those cells, so it reads their current values each time it's called, as in Python.
    • A lambda can use the variables of every function it's nested in.
    • 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. To run its element, it puts back the function's bindings the comprehension's loop variables replaced, and swaps them again afterwards. An assignment in the element (for example with :=) sets the value of the function's variable and doesn't replace its binding, so nothing needs copying back.
  • At the end of an except block its name is unbound like del, so a lambda or inner function sharing it sees that too.
  • Annotated assignments make local variables.
  • Functions without an inner function or lambda handle comprehensions as before, with one fix: when a list, dict or set comprehension raises, the function's variable with the same name as its loop variable is now put back. Before, the loop variable was left in its place.

Changes since review

  • Rebased on master after Support super().prop for pyscript properties #923. The only clash was at the end of 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.
  • A second commit removes LoopScope.keep_writes() and its call in genexp_loop. I ran each case three ways: in CPython, in this PR with keep_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 or nonlocal inner function). All of them give the same result with and without keep_writes(), and with a check that fails whenever keep_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 the global one still differ from Python, with and without keep_writes() (see the Note). In a function that shares its variables, every name the function binds already has its EvalLocalVar when 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

  • New test_lambdas_match_python in tests/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, map and filter keys, walrus and del, except names, and error cases. Two of them check super() 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, and super() in comprehensions, generator expressions and inner functions. Three check lambdas in the @property and @classmethod methods 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 (including cls) and see later changes to them; lambdas made in comprehensions and generator expressions in those methods, reusing loop names (including cls); and lambdas used as property getters and setters (property(lambda self: ...)) that use the variables of the function they're made in.
  • New 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 in LAMBDA_TESTS above.)
  • New 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 through zip, and next() in a comprehension), an element that raises before or after its :=, and a global name. The 15th has no :=: the element calls an inner function that assigns the name with nonlocal, then one that deletes it, while a comprehension with that loop name runs the generator expression. They pass with and without keep_writes().
  • In all, 94 scripts compared with CPython.
  • The full test suite (232 tests), ruff, pylint, mypy, codespell and sphinx-build -W pass 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.
  • The Language Limitations item on generator expressions now says that the loop-variable differences apply at module level, that a generator expression made in another one's element or in a list comprehension doesn't see the outer loop variables once the outer one isn't running, and that a generator expression used by a comprehension sees the comprehension's loop variables unless it was made in a function with an inner function or lambda.

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>'.
  • Comprehensions at module level are unchanged.
  • Functions without inner functions or lambdas keep the existing comprehension behaviour, now documented. So a generator expression used by a comprehension that reuses a name sees the comprehension's loop variable, and a := to that name is lost. For example, x = 0; g = ((x := x + 1) for _ in range(3)); r = [x for x in g] leaves x at 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.
  • A comprehension target that is declared nonlocal or global can still change the outer variable where Python keeps it. This was already the case.
  • If an inner function returns a lambda using a variable the outer function hasn't assigned yet, the lambda stays unbound after the outer function assigns it. This was already the case.
  • A class body inside a function doesn't see the function's variables, so x = property(lambda self: n) written in such a class body raises NameError for n when the property is read. This was already the case, for any use of those variables in a class body, not only lambdas.
  • A lambda that reads a pyscript property (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.
  • As the docs have said since Support super(), Base.__init__ and inherited __init__ in pyscript classes (#891) #916, super() without arguments doesn't work in a lambda (Python finds the lambda's first argument); super(Cls, self) does.
  • Open edge case: a lambda that contains __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 through eval() or locals().

This PR is rebased on master after #923. It and my StopIteration PR (#920) both change eval.py, so they still clash with each other. Whichever merges second needs a rebase, about 6 hunks, in ast_lambda, try_handlers, loopvar_scope_save and the list, dict and set comprehension loops. I'm happy to do it. Both PRs also add tests at the end of tests/test_unit_eval.py, which is a small "keep both" conflict.

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

Thanks @craigbarratt, for the review and for spotting that.

keep_writes(): you were right, nothing needs it, so I've removed it. I ran each case three ways: in CPython, in this PR as it was, and with keep_writes() removed, in a function with an inner lambda and, where the case allows it, in one without. Every case gives the same result with and without it. I also ran the full test suite and all the cases with keep_writes() changed to fail whenever it found something to keep, and nothing failed.

Here's why it's never needed. In a function that shares its variables, every name the function binds (including := targets and comprehension loop names) already has its EvalLocalVar when the function is called. A := in the element sets that variable's value and doesn't replace the binding, so the saved binding already holds the new value. Nested comprehensions and generator expressions in the element always put back the bindings they replace when they finish, even when they raise. So there's never a changed binding for keep_writes() to keep.

What changed, in a second commit on top of the original one so you can see it on its own:

  • custom_components/pyscript/eval.py: removed LoopScope.keep_writes() and its call in genexp_loop, with a comment there saying why nothing needs copying back.
  • tests/test_unit_eval.py: new GENEXP_WALRUS_SCOPE_TESTS, run by test_genexp_walrus_scopes_match_python. These are 15 scripts compared with CPython, each run in a function with an inner function. 14 have a := in a generator expression run by a later comprehension that reuses the 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 through zip, next() in a comprehension), an element that raises before or after its :=, and a global name. The 15th has no :=: the element calls inner functions that assign and then delete the name with nonlocal. They pass with and without keep_writes(), so they guard the behaviour rather than keep_writes() itself. I also ran by hand the cases that can be written without an inner function or lambda (all but the four that use one) in a function without one. Those aren't committed tests, because all but the global one still differ from Python (below).

I've also rebased the PR on master after #923. The only clash was the tests both PRs add at the end of tests/test_unit_eval.py, and I kept both sets.

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 := to that name is lost. For example:

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: ZeroDivisionError

Adding a lambda to any of these functions (for example _read = lambda: x) makes them match Python. These differences were already there before this PR, and using the new scoping in every function changes how every function's comprehensions run, so I'd do it as a separate PR.

@craigbarratt
craigbarratt merged commit 0149ea9 into custom-components:master Nov 22, 2026
6 checks passed
craigbarratt pushed a commit that referenced this pull request Nov 23, 2026
…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>
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.

Unable to use pyfunctional in modules

2 participants