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

Respect duplicates when rewriting type aliases #9905

Merged
merged 1 commit into from
Feb 9, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pyupgrade/UP040.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,8 @@ class Foo:
# OK
x: TypeAlias
x: int = 1

# Ensure that "T" appears only once in the type parameters for the modernized
# type alias.
T = typing.TypeVar["T"]
Decorator: TypeAlias = typing.Callable[[T], T]
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use itertools::Itertools;

use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{
Expand Down Expand Up @@ -92,20 +94,27 @@ pub(crate) fn non_pep695_type_alias(checker: &mut Checker, stmt: &StmtAnnAssign)

// TODO(zanie): We should check for generic type variables used in the value and define them
// as type params instead
let mut diagnostic = Diagnostic::new(NonPEP695TypeAlias { name: name.clone() }, stmt.range());
let mut visitor = TypeVarReferenceVisitor {
vars: vec![],
semantic: checker.semantic(),
let vars = {
let mut visitor = TypeVarReferenceVisitor {
vars: vec![],
semantic: checker.semantic(),
};
visitor.visit_expr(value);
visitor.vars
};
visitor.visit_expr(value);

let type_params = if visitor.vars.is_empty() {
// Type variables must be unique; filter while preserving order.
let vars = vars
.into_iter()
.unique_by(|TypeVar { name, .. }| name.id.as_str())
.collect::<Vec<_>>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Itertools is already in scope, you could avoid the turbofish here:

Suggested change
.collect::<Vec<_>>();
.collect_vec();

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a habit, I try to avoid using Itertools where it's not providing much value since it (1) makes it a little easier if we remove the dep in the future and (2) in my opinion at least it's actually easier to read the explicit version.


let type_params = if vars.is_empty() {
None
} else {
Some(ast::TypeParams {
range: TextRange::default(),
type_params: visitor
.vars
type_params: vars
.into_iter()
.map(|TypeVar { name, restriction }| {
TypeParam::TypeVar(TypeParamTypeVar {
Expand All @@ -128,6 +137,8 @@ pub(crate) fn non_pep695_type_alias(checker: &mut Checker, stmt: &StmtAnnAssign)
})
};

let mut diagnostic = Diagnostic::new(NonPEP695TypeAlias { name: name.clone() }, stmt.range());

let edit = Edit::range_replacement(
checker.generator().stmt(&Stmt::from(StmtTypeAlias {
range: TextRange::default(),
Expand All @@ -137,16 +148,15 @@ pub(crate) fn non_pep695_type_alias(checker: &mut Checker, stmt: &StmtAnnAssign)
})),
stmt.range(),
);

// The fix is only safe in a type stub because new-style aliases have different runtime behavior
// See https://github.com/astral-sh/ruff/issues/6434
let fix = if checker.source_type.is_stub() {
Fix::safe_edit(edit)
} else {
Fix::unsafe_edit(edit)
};

diagnostic.set_fix(fix);

checker.diagnostics.push(diagnostic);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,4 +230,20 @@ UP040.py:44:1: UP040 [*] Type alias `x` uses `TypeAlias` annotation instead of t
46 46 | # OK
47 47 | x: TypeAlias

UP040.py:53:1: UP040 [*] Type alias `Decorator` uses `TypeAlias` annotation instead of the `type` keyword
|
51 | # type alias.
52 | T = typing.TypeVar["T"]
53 | Decorator: TypeAlias = typing.Callable[[T], T]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UP040
|
= help: Use the `type` keyword

ℹ Unsafe fix
50 50 | # Ensure that "T" appears only once in the type parameters for the modernized
51 51 | # type alias.
52 52 | T = typing.TypeVar["T"]
53 |-Decorator: TypeAlias = typing.Callable[[T], T]
53 |+type Decorator[T] = typing.Callable[[T], T]