Fix invalid E231 error with f-strings (#8369)

## Summary

We were considering the `{` within an f-string to be a left brace, which
caused the "space-after-colon" rule to trigger incorrectly.

Closes https://github.com/astral-sh/ruff/issues/8299.
This commit is contained in:
Charlie Marsh 2023-10-30 16:38:13 -07:00 committed by GitHub
parent 7323c12eee
commit c674db6e51
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 3 deletions

View file

@ -40,5 +40,11 @@ f"{(a:=1)}"
f"{(lambda x:x)}" f"{(lambda x:x)}"
f"normal{f"{a:.3f}"}normal" f"normal{f"{a:.3f}"}normal"
#: Okay
snapshot.file_uri[len(f's3://{self.s3_bucket_name}/'):]
#: E231
{len(f's3://{self.s3_bucket_name}/'):1}
#: Okay #: Okay
a = (1, a = (1,

View file

@ -64,14 +64,14 @@ pub(crate) fn missing_whitespace(line: &LogicalLine, context: &mut LogicalLinesC
match kind { match kind {
TokenKind::FStringStart => fstrings += 1, TokenKind::FStringStart => fstrings += 1,
TokenKind::FStringEnd => fstrings = fstrings.saturating_sub(1), TokenKind::FStringEnd => fstrings = fstrings.saturating_sub(1),
TokenKind::Lsqb => { TokenKind::Lsqb if fstrings == 0 => {
open_parentheses = open_parentheses.saturating_add(1); open_parentheses = open_parentheses.saturating_add(1);
prev_lsqb = token.start(); prev_lsqb = token.start();
} }
TokenKind::Rsqb => { TokenKind::Rsqb if fstrings == 0 => {
open_parentheses = open_parentheses.saturating_sub(1); open_parentheses = open_parentheses.saturating_sub(1);
} }
TokenKind::Lbrace => { TokenKind::Lbrace if fstrings == 0 => {
prev_lbrace = token.start(); prev_lbrace = token.start();
} }
TokenKind::Colon if fstrings > 0 => { TokenKind::Colon if fstrings > 0 => {

View file

@ -121,4 +121,24 @@ E23.py:33:6: E231 [*] Missing whitespace after ','
35 35 | # Okay because it's hard to differentiate between the usages of a colon in a f-string 35 35 | # Okay because it's hard to differentiate between the usages of a colon in a f-string
36 36 | f"{a:=1}" 36 36 | f"{a:=1}"
E23.py:47:37: E231 [*] Missing whitespace after ':'
|
46 | #: E231
47 | {len(f's3://{self.s3_bucket_name}/'):1}
| ^ E231
48 |
49 | #: Okay
|
= help: Add missing whitespace
Fix
44 44 | snapshot.file_uri[len(f's3://{self.s3_bucket_name}/'):]
45 45 |
46 46 | #: E231
47 |-{len(f's3://{self.s3_bucket_name}/'):1}
47 |+{len(f's3://{self.s3_bucket_name}/'): 1}
48 48 |
49 49 | #: Okay
50 50 | a = (1,