Skip to content

B023 is emitted when closure is defined inside a loop and uses a variable from the same loop #7847

@Guilherme-Vasconcelos

Description

@Guilherme-Vasconcelos

Code snippet that reproduces the bug

The following snippet emits B023 (function-uses-loop-variable):

def make_squared_list(size: int) -> list[int]:
    result = []

    for i in range(size):
        square = i**2

        def _append_to_result() -> None:
            # Function definition does not bind loop variable `square` Ruff[B023](https://docs.astral.sh/ruff/rules/function-uses-loop- 
            # variable)
            # (variable) square: int
            result.append(square)

        _append_to_result()

    return result

I have found out that adding a nonlocal <variable> declaration followed by an assignment to itself makes the error go away, i.e. change the closure _append_to_result to this:

def _append_to_result() -> None:
    # No longer emits any warnings.
    nonlocal square
    square = square
    result.append(square)

Command invoked

$ poetry run ruff ./ruff_bug.py

Current ruff settings

Relevant sections from pyproject.toml:

[tool.ruff]
select = [
    "F",
    "E",
    "W",
    "I",
    "N",
    "UP",
    "S",
    "BLE",
    "B",
    "A",
    "C4",
    "SIM",
    "PERF",
    "RUF"
]
line-length = 88
target-version = "py311"
ignore = [
    "S101",
    "B011",
]

[tool.ruff.pycodestyle]
ignore-overlong-task-comments = true

Current ruff version

$ poetry run ruff --version
ruff 0.0.291

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions