Skip to content

Conversation

@sohamukute
Copy link

Summary

Fixes a bug in the FURB142 (for-loop-set-mutations) fixer where an unparenthesized generator expression used as the .add(...) argument would be inlined into the rewritten comprehension without parentheses, changing variable scoping and causing a runtime NameError.

Before (problematic after fix):

s = set()
for x in ("abc", "def"):
    s.add(c for c in x)
# fixed to:
s.update(c for c in x for x in ("abc", "def"))  # NameError: x

After (correct, parenthesized):

s = set()
for x in ("abc", "def"):
    s.add(c for c in x)
# fixed to:
s.update((c for c in x) for x in ("abc", "def"))

Implementation details:

  • In the “comprehension” rewrite path of FURB142, detect Expr::Generator arguments that are not already parenthesized and wrap them with parentheses in the generated replacement string.
  • Leaves already-parenthesized generator expressions unchanged.
  • Leaves non-generator arguments unchanged.
  • Maintains existing applicability handling and comment-safety behavior.

References:

Test Plan

  • Repro the original failing case and confirm the new fix:

    1. Create the file:

      s = set()
      for x in ("abc", "def"):
          s.add(c for c in x)
    2. Verify Ruff flags it:

      cargo run -p ruff_cli -- check --isolated --select FURB142 --preview furb142.py
      
    3. Apply the fix:

      cargo run -p ruff_cli -- check --isolated --select FURB142 --preview --fix furb142.py
      
    4. Inspect output (should contain parentheses):

      s.update((c for c in x) for x in ("abc", "def"))
      
    5. Run the file:

      python furb142.py
      

      Expect no NameError.

- Fixes astral-sh#21098.
- When rewriting set.add(...) calls inside for-loops into set.update(...), wrap an unparenthesized generator-expression argument in parentheses to avoid altering scope and causing NameError.
- Adds targeted logic in for_loop_set_mutations to detect Expr::Generator with parenthesized == false and parenthesize its source text.
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.

FURB142 fix should parenthesize generator expressions

1 participant