PyCQA / PyCQA/flake8-bugbear

Proposed warning: reuse of loop variable in nested loop

Open
#360 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
123
Avg merge
2d 5h
Merged PRs (30d)
5

Description

I was just bitten by a bug in production where I accidentally reused an outer loop variable in a nested loop. Example:

# Outer loop.
for i in range(10):
    # Enough code here to hide the outermost loop off screen.
    # ...

    # Developer does not notice "i" is already being used as a loop variable
    # and accidentally overwrites it here. The type is the same, so type checkers
    # don't complain.
    for i in range(10):
        print(f"inner loop {i=}")

    # Enough code here to hide the innermost loop off screen.
    # ...

    # Developer expects "i" to still hold the value of the outer loop.
    # Instead, the value is always 9.
    print(f"outer loop {i=}")

Proposed warning: B???: "Variable 'i' is already declared in 'for' loop or 'with' statement above"

Credit for the wording: this is one of PyCharm's built-in inspections.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or entry points are named. Start by tracing how existing flake8-bugbear warnings detect loop and with-statement variables, then identify the relevant test location and add coverage for the nested-loop example; done means the proposed warning is emitted for accidental reuse without flagging valid cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.