mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-29 13:25:17 +00:00
[ruff] Skip tuples with slice expressions in incorrectly-parenthesized-tuple-in-subscript (RUF031)
(#12768)
## Summary Adding parentheses to a tuple in a subscript with elements that include slice expressions causes a syntax error. For example, `d[(1,2,:)]` is a syntax error. So, when `lint.ruff.parenthesize-tuple-in-subscript = true` and the tuple includes a slice expression, we skip this check and fix. Closes #12766.
This commit is contained in:
parent
ffaa35eafe
commit
64f1f3468d
5 changed files with 17 additions and 3 deletions
|
@ -27,3 +27,5 @@ token_features[
|
|||
d[1,]
|
||||
d[(1,)]
|
||||
d[()] # empty tuples should be ignored
|
||||
d[:,] # slices in the subscript lead to syntax error if parens are added
|
||||
d[1,2,:]
|
|
@ -26,3 +26,6 @@ token_features[
|
|||
d[1,]
|
||||
d[(1,)]
|
||||
d[()] # empty tuples should be ignored
|
||||
|
||||
d[:,] # slices in the subscript lead to syntax error if parens are added
|
||||
d[1,2,:]
|
|
@ -1,6 +1,6 @@
|
|||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
|
||||
use ruff_macros::{derive_message_formats, violation};
|
||||
use ruff_python_ast::ExprSubscript;
|
||||
use ruff_python_ast::{Expr, ExprSubscript};
|
||||
use ruff_text_size::Ranged;
|
||||
|
||||
use crate::checkers::ast::Checker;
|
||||
|
@ -64,6 +64,10 @@ pub(crate) fn subscript_with_parenthesized_tuple(checker: &mut Checker, subscrip
|
|||
if tuple_subscript.parenthesized == prefer_parentheses || tuple_subscript.elts.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Adding parentheses in the presence of a slice leads to a syntax error.
|
||||
if prefer_parentheses && tuple_subscript.elts.iter().any(Expr::is_slice_expr) {
|
||||
return;
|
||||
}
|
||||
let locator = checker.locator();
|
||||
let source_range = subscript.slice.range();
|
||||
let new_source = if prefer_parentheses {
|
||||
|
|
|
@ -156,6 +156,7 @@ RUF031.py:28:3: RUF031 [*] Avoid parentheses for tuples in subscripts.
|
|||
28 | d[(1,)]
|
||||
| ^^^^ RUF031
|
||||
29 | d[()] # empty tuples should be ignored
|
||||
30 | d[:,] # slices in the subscript lead to syntax error if parens are added
|
||||
|
|
||||
= help: Remove the parentheses.
|
||||
|
||||
|
@ -166,3 +167,5 @@ RUF031.py:28:3: RUF031 [*] Avoid parentheses for tuples in subscripts.
|
|||
28 |-d[(1,)]
|
||||
28 |+d[1,]
|
||||
29 29 | d[()] # empty tuples should be ignored
|
||||
30 30 | d[:,] # slices in the subscript lead to syntax error if parens are added
|
||||
31 31 | d[1,2,:]
|
||||
|
|
|
@ -129,3 +129,5 @@ RUF031_prefer_parens.py:26:3: RUF031 [*] Use parentheses for tuples in subscript
|
|||
27 26 | d[(1,)]
|
||||
27 |+d[(1,)]
|
||||
28 28 | d[()] # empty tuples should be ignored
|
||||
29 29 |
|
||||
30 30 | d[:,] # slices in the subscript lead to syntax error if parens are added
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue