mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-25 02:55:35 +08:00
## Summary
Python rejects assignment expressions in several comprehension contexts,
but we previously only reported the case in which a walrus rebound a
comprehension variable.
As a result, we accepted invalid walruses in the iterable and class-body
portions clause of a comprehension, and missed some rebinding cases in
filter clauses and nested comprehensions. It turns out the rules are
really complicated!
For example, we now report the two newly modeled syntax errors:
```py
# error: [invalid-syntax] "assignment expression cannot be used in a comprehension iterable expression"
[x for x in (values := [1])]
class C:
# error: [invalid-syntax] "assignment expression within a comprehension cannot be used in a class body"
[(value := item) for item in [1]]
```
We also catch previously missed instances of the existing rebinding
error:
```py
# error: [invalid-syntax] "assignment expression cannot rebind comprehension variable"
[x for x in [1] if (x := 0)]
```
In general, I decided not to worry about emitting multiple diagnostics
for a single error. These are rare, they're fatal, and it added a lot of
complexity (so in some cases we may emit two errors for a walrus that is
invalid for two reasons).
Ruff Python Parser
Ruff's Python parser is a hand-written recursive descent parser which can parse Python source code into an Abstract Syntax Tree (AST). It also utilizes the Pratt parsing technique to parse expressions with different precedence.
Try out the parser in the playground.
Python version support
The parser supports the latest Python syntax, which is currently Python 3.12.
It does not throw syntax errors if it encounters a syntax feature that is not
supported by the target-version.
This will be fixed in a future release (see https://github.com/astral-sh/ruff/issues/6591).
Contributing
Refer to the contributing guidelines to get started and GitHub issues with the parser label for issues that need help.