Skip to content

[mypyc] Fix lambdas in generator expressions consumed by builtins - #22225

Merged
JukkaL merged 2 commits into
masterfrom
mypycp-fix-generator-scope
Oct 19, 2026
Merged

JukkaL merged 2 commits into
masterfrom
mypycp-fix-generator-scope

Conversation

@JukkaL

@JukkaL JukkaL commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

A generator expression that contains a lambda needs a lightweight
comprehension scope so that the lambda can capture the loop variables.
The special cases for tuple(), set(), sum(), any(), all(), next() and
other builtins that consume a generator expression didn't set up the
scope, so calling such a lambda raised UnboundLocalError, e.g.
tuple((lambda: x) for x in range(3)).

Move the scope helper to for_helpers.comprehension_scope and use it in
all these special cases.

This fixes a regression from #21009.

Also fix a few other closely related issues that came up when testing
the fix.

Add significant test coverage since these features seem to have a
high density of issues.

A generator expression that contains a lambda needs a lightweight
comprehension scope so that the lambda can capture the loop variables.
The special cases for tuple(), set(), sum(), any(), all(), next() and
other builtins that consume a generator expression didn't set up the
scope, so calling such a lambda raised UnboundLocalError, e.g.
tuple((lambda: x) for x in range(3)).

Move the scope helper to for_helpers.comprehension_scope and use it in
all these special cases.

This fixes a regression from #21009
(#21009).
Comment on lines +416 to +420
if node not in builder.comprehension_to_fitem:
yield
return

comprehension_fdef = builder.comprehension_to_fitem[node]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

could avoid the second look-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'm leaving it as is since this isn't perf critical and the code seems clear.

@JukkaL
JukkaL merged commit b680404 into master Oct 19, 2026
18 checks passed
@JukkaL
JukkaL deleted the mypycp-fix-generator-scope branch October 19, 2026 11:25
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.

2 participants