Skip to content

[Fix error] C417 and walrus statements #14808

@zeevox

Description

@zeevox

Applying fixes for rule C417 introduces a syntax error when the second map argument is a walrus assignment operator.

Minimal example below.
I'm using ruff 0.8.2 and Python 3.12.7 to test this.
For a more complete example, this issue first arose in my solution to Advent of Code 2019 Day 3.

a = [1, 2, 3]
b = map(lambda x: x, c := a)
print(c)

Fix applied by ruff check test.py --select C417 --fix --unsafe-fixes

-b = map(lambda x: x, c := a)
+b = (x for x in c := a)

is syntactically incorrect

  File "/home/zeevox/test.py", line 2
    b = (x for x in c := a)
                      ^^
SyntaxError: invalid syntax

You would think wrapping the walrus statement in parentheses would suffice, like

b = (x for x in (c := a))

And indeed, ruff believes all is well

% ruff check test.py --select C417
All checks passed!

but this too, in fact, raises a syntax error

  File "/home/zeevox/test.py", line 2
    b = (x for x in (c := a))
                     ^^^^^^
SyntaxError: assignment expression cannot be used in a comprehension iterable expression

I wonder whether the real solution is to extract the assignment onto the previous line, or not show the warning in the first place.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violationshelp wantedContributions especially welcome

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions