Skip to content

Commit

Permalink
[pyupgrade] - ignore kwarg unpacking for UP044 (#14053)
Browse files Browse the repository at this point in the history
## Summary

Fixes #14047 

## Test Plan

`catgo test`

---------

Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
  • Loading branch information
diceroll123 and charliermarsh authored Nov 2, 2024
1 parent 70bdde4 commit 0925513
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
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

0 comments on commit 0925513

Please sign in to comment.