Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pyupgrade] - ignore kwarg unpacking for UP044 #14053

Merged
merged 2 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pyupgrade/UP044.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,11 @@ def f(*args: Unpack[other.Type]): pass
def foo(*args: Unpack[int | str]) -> None: pass
def foo(*args: Unpack[int and str]) -> None: pass
def foo(*args: Unpack[int > str]) -> None: pass

# We do not use the shorthand unpacking syntax in the following cases
from typing import TypedDict
class KwargsDict(TypedDict):
x: int
y: int

def foo(name: str, /, **kwargs: Unpack[KwargsDict]) -> None: pass
22 changes: 19 additions & 3 deletions crates/ruff_linter/src/rules/pyupgrade/rules/use_pep646_unpack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{checkers::ast::Checker, settings::types::PythonVersion};
/// ## Why is this bad?
/// [PEP 646] introduced a new syntax for unpacking sequences based on the `*`
/// operator. This syntax is more concise and readable than the previous
/// `typing.Unpack` syntax.
/// `Unpack[]` syntax.
///
/// ## Example
///
Expand All @@ -30,8 +30,7 @@ use crate::{checkers::ast::Checker, settings::types::PythonVersion};
/// pass
/// ```
///
/// ## References
/// - [PEP 646](https://peps.python.org/pep-0646/#unpack-for-backwards-compatibility)
/// [PEP 646]: https://peps.python.org/pep-0646/
#[violation]
pub struct NonPEP646Unpack;

Expand All @@ -58,6 +57,23 @@ pub(crate) fn use_pep646_unpack(checker: &mut Checker, expr: &ExprSubscript) {
return;
}

// Ignore `kwarg` unpacking, as in:
// ```python
// def f(**kwargs: Unpack[Array]):
// ...
// ```
if checker
.semantic()
.current_statement()
.as_function_def_stmt()
.and_then(|stmt| stmt.parameters.kwarg.as_ref())
.and_then(|kwarg| kwarg.annotation.as_ref())
.and_then(|annotation| annotation.as_subscript_expr())
.is_some_and(|subscript| subscript == expr)
{
return;
}

let ExprSubscript {
range,
value,
Expand Down
Loading