Skip to content

fix(linter): suppress FURB122 fix when walrus operator rebinds loop variable#24566

Open
hijingsong wants to merge 1 commit intoastral-sh:mainfrom
hijingsong:clawoss/fix/furb122-walrus-rebinding
Open

fix(linter): suppress FURB122 fix when walrus operator rebinds loop variable#24566
hijingsong wants to merge 1 commit intoastral-sh:mainfrom
hijingsong:clawoss/fix/furb122-walrus-rebinding

Conversation

@hijingsong
Copy link
Copy Markdown

Summary

Suppresses the FURB122 (for-loop-writes) fix when the .write() argument contains a walrus operator (:=) whose target is one of the for-loop's iteration variables.

The fix would otherwise generate an invalid comprehension. For example:

for line in src:
    dst.write(line := line.upper())

would be transformed to:

dst.writelines(line := line.upper() for line in src)

which produces SyntaxError: assignment expression cannot rebind comprehension iteration variable 'line'.

Similarly for tuple unpacking:

for first, *rest in src:
    dst.write(rest := "".join(rest))

Test Plan

Added test cases to FURB122.py fixture:

  1. Suppressed: dst.write(line := line.upper()) where line is the loop variable
  2. Suppressed: dst.write(rest := "".join(rest)) where rest is a loop variable from tuple unpacking
  3. Still triggers: f.write(y := process(x)) where y is NOT a loop variable — the fix is still valid here

Closes: #21107

…ariable

When the argument to `.write()` in a for-loop contains a walrus operator
(:=) whose target is one of the for-loop's iteration variables, the
FURB122 fix would generate an invalid comprehension. For example:

    for line in src:
        dst.write(line := line.upper())

would be transformed to:

    dst.writelines(line := line.upper() for line in src)

which is a SyntaxError because the walrus operator cannot rebind a
comprehension iteration variable.

Suppress the fix in such cases by detecting walrus operators in the
write argument whose targets match any for-loop binding names.

Closes: astral-sh#21107
found: bool,
}

impl<'a> Visitor<'a> for WalrusChecker<'a> {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You can use any_over_expr over writing your own visitor. I also suggest you take a look at the previous PRs trying to fix this issue. Maybe there's some test cases or edge cases that are worth copying over:)

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.

FURB122 fix introduces syntax error for rebound comprehension variable

4 participants