Skip to content

B023: don't flag a lambda that is called where it is defined - #638

Merged
cooperlees merged 1 commit into
PyCQA:mainfrom
Kernel-Hunter:b023-immediately-called-lambda
Nov 18, 2026
Merged

cooperlees merged 1 commit into
PyCQA:mainfrom
Kernel-Hunter:b023-immediately-called-lambda

Conversation

@Kernel-Hunter

Copy link
Copy Markdown
Contributor

B023 flags a lambda that is called on the spot, even though it cannot outlive the iteration:

for i in range(3):
    x = i
    results.append((lambda: x)())
B023 Function definition does not bind loop variable 'x'.

The lambda runs to completion before the next iteration, so reading x is not the late-binding problem the rule is about. #567 already exempted a named function that is only called inside the loop, and map/filter/reduce/key= lambdas are exempt too. This adds the same exemption for (lambda: ...)().

I kept the exemption narrow. A lambda that yields, or whose body contains a generator expression, only builds a generator when it is called, so those are still reported, and so is a lambda returned from the called lambda. Cases for all of them are in tests/eval_files/b023.py, and the README changelog has an entry. The new test cases fail without the change and the rest of the suite is unchanged (the two test_selfclean_* tests fail on main in my checkout too, with a FileNotFoundError).

@cooperlees cooperlees left a comment

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.

This review was written by Claude (Anthropic's AI assistant) on behalf of @cooperlees.

Thanks @Kernel-Hunter. This looks good to me, and the exemption is scoped about right.

What I checked

  • ast.walk is breadth-first, so the Call is visited before its Lambda child. That means the lambda is already in safe_functions by the time the "find unsafe functions" branch reaches it. 👍
  • The only expression-level constructs that delay evaluation past the call are nested lambdas, yield/yield from, and generator expressions. Nested lambdas are still visited and checked on their own, and the other two are excluded by your ast.walk guard. List, set and dict comprehensions run eagerly, so it's right not to exclude them.
  • On the PR branch, pytest tests -k "not selfclean" gives 161 passed, 3 skipped.
  • I also ran some extra cases against the branch:
    for i in range(3):
        x = i
        (lambda: x)()                              # not flagged ✅
        (lambda: [x for _ in "ab"])()              # not flagged ✅ (listcomp is eager)
        (lambda: (lambda: x)())()                  # not flagged ✅
        f = (lambda: x)                            # flagged ✅ (escapes)
        (lambda: sum(x for _ in "a"))()            # flagged (see nit)
        (lambda: (lambda: (yield x)))()            # flagged ✅

Non-blocking nit
The GeneratorExp guard is conservative. (lambda: sum(x for _ in y))() still warns even though the genexp is consumed before the lambda returns. That's a reasonable trade-off for keeping the check simple, and a false positive is better than a missed late-binding bug. It might be worth a short comment there so nobody "fixes" it later without thinking about the cases where the genexp escapes.

Approving.

@cooperlees
cooperlees merged commit b5d6a3c into PyCQA:main Nov 18, 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.

2 participants