Fix named expression precedence in generator (#7170)

This commit is contained in:
Charlie Marsh 2023-09-05 19:06:57 +02:00 committed by GitHub
parent 89be850b73
commit f8e4e1d562
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 1 deletions

View file

@ -138,3 +138,12 @@ def scope():
class TemperatureScales(Enum):
CELSIUS = (lambda deg_c: deg_c)
FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32)
# Regression test for: https://github.com/astral-sh/ruff/issues/7141
def scope():
# E731
f = lambda: (
i := 1,
)

View file

@ -339,6 +339,8 @@ E731.py:139:5: E731 [*] Do not assign a `lambda` expression, use a `def`
139 |+ def CELSIUS(deg_c):
140 |+ return deg_c
140 141 | FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32)
141 142 |
142 143 |
E731.py:140:5: E731 [*] Do not assign a `lambda` expression, use a `def`
|
@ -356,5 +358,30 @@ E731.py:140:5: E731 [*] Do not assign a `lambda` expression, use a `def`
140 |- FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32)
140 |+ def FAHRENHEIT(deg_c):
141 |+ return deg_c * 9 / 5 + 32
141 142 |
142 143 |
143 144 | # Regression test for: https://github.com/astral-sh/ruff/issues/7141
E731.py:147:5: E731 [*] Do not assign a `lambda` expression, use a `def`
|
145 | # E731
146 |
147 | f = lambda: (
| _____^
148 | | i := 1,
149 | | )
| |_____^ E731
|
= help: Rewrite `f` as a `def`
Suggested fix
144 144 | def scope():
145 145 | # E731
146 146 |
147 |- f = lambda: (
148 |- i := 1,
149 |- )
147 |+ def f():
148 |+ return (i := 1),

View file

@ -14,6 +14,7 @@ use ruff_source_file::LineEnding;
use super::stylist::{Indentation, Quote, Stylist};
mod precedence {
pub(crate) const NAMED_EXPR: u8 = 1;
pub(crate) const ASSIGN: u8 = 3;
pub(crate) const ANN_ASSIGN: u8 = 5;
pub(crate) const AUG_ASSIGN: u8 = 5;
@ -30,7 +31,6 @@ mod precedence {
pub(crate) const TUPLE: u8 = 19;
pub(crate) const FORMATTED_VALUE: u8 = 19;
pub(crate) const COMMA: u8 = 21;
pub(crate) const NAMED_EXPR: u8 = 23;
pub(crate) const ASSERT: u8 = 23;
pub(crate) const COMPREHENSION_ELEMENT: u8 = 27;
pub(crate) const LAMBDA: u8 = 27;
@ -1639,6 +1639,13 @@ class Foo:
"class SchemaItem(NamedTuple):
fields: ((\"property_key\", str),)"
);
assert_round_trip!(
"def func():
return (i := 1)"
);
assert_round_trip!("yield (i := 1)");
assert_round_trip!("x = (i := 1)");
assert_round_trip!("x += (i := 1)");
// Type aliases
assert_round_trip!(r#"type Foo = int | str"#);