Avoid flagging starred expressions in UP007 (#7505)

## Summary

These can't be fixed, because fixing them would lead to invalid syntax.
So flagging them also feels misleading.

Closes https://github.com/astral-sh/ruff/issues/7452.
This commit is contained in:
Charlie Marsh 2023-09-18 23:37:38 -04:00 committed by GitHub
parent 4123d074bd
commit 28b48ab902
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 1 deletions

View file

@ -143,7 +143,7 @@ pub fn to_pep604_operator(
slice: &Expr,
semantic: &SemanticModel,
) -> Option<Pep604Operator> {
/// Returns `true` if any argument in the slice is a quoted annotation).
/// Returns `true` if any argument in the slice is a quoted annotation.
fn quoted_annotation(slice: &Expr) -> bool {
match slice {
Expr::Constant(ast::ExprConstant {
@ -155,6 +155,15 @@ pub fn to_pep604_operator(
}
}
/// Returns `true` if any argument in the slice is a starred expression.
fn starred_annotation(slice: &Expr) -> bool {
match slice {
Expr::Starred(_) => true,
Expr::Tuple(ast::ExprTuple { elts, .. }) => elts.iter().any(starred_annotation),
_ => false,
}
}
// If the slice is a forward reference (e.g., `Optional["Foo"]`), it can only be rewritten
// if we're in a typing-only context.
//
@ -175,6 +184,14 @@ pub fn to_pep604_operator(
}
}
// If any of the elements are starred expressions, we can't rewrite the subscript:
// ```python
// def f(x: Union[*int, str]): ...
// ```
if starred_annotation(slice) {
return None;
}
semantic
.resolve_call_path(value)
.as_ref()