Skip to content

Commit 2ab1502

Browse files
authored
[ty] Improve the Display for generic type[] types (#19667)
1 parent a3f28ba commit 2ab1502

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

crates/ty_python_semantic/resources/mdtest/type_of/basic.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,28 @@ class Foo(type[int]): ...
151151
reveal_type(Foo.__mro__) # revealed: tuple[<class 'Foo'>, @Todo(GenericAlias instance), <class 'object'>]
152152
```
153153

154+
## Display of generic `type[]` types
155+
156+
```toml
157+
[environment]
158+
python-version = "3.12"
159+
```
160+
161+
```py
162+
from typing import Generic, TypeVar
163+
164+
class Foo[T]: ...
165+
166+
S = TypeVar("S")
167+
168+
class Bar(Generic[S]): ...
169+
170+
def _(x: Foo[int], y: Bar[str], z: list[bytes]):
171+
reveal_type(type(x)) # revealed: type[Foo[int]]
172+
reveal_type(type(y)) # revealed: type[Bar[str]]
173+
reveal_type(type(z)) # revealed: type[list[bytes]]
174+
```
175+
154176
## `@final` classes
155177

156178
`type[]` types are eagerly converted to class-literal types if a class decorated with `@final` is

crates/ty_python_semantic/src/types/display.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,12 @@ impl Display for DisplayRepresentation<'_> {
109109
}
110110
Type::GenericAlias(generic) => write!(f, "<class '{}'>", generic.display(self.db)),
111111
Type::SubclassOf(subclass_of_ty) => match subclass_of_ty.subclass_of() {
112-
// Only show the bare class name here; ClassBase::display would render this as
113-
// type[<class 'Foo'>] instead of type[Foo].
114-
SubclassOfInner::Class(class) => write!(f, "type[{}]", class.name(self.db)),
112+
SubclassOfInner::Class(ClassType::NonGeneric(class)) => {
113+
write!(f, "type[{}]", class.name(self.db))
114+
}
115+
SubclassOfInner::Class(ClassType::Generic(alias)) => {
116+
write!(f, "type[{}]", alias.display(self.db))
117+
}
115118
SubclassOfInner::Dynamic(dynamic) => write!(f, "type[{dynamic}]"),
116119
},
117120
Type::SpecialForm(special_form) => special_form.fmt(f),

0 commit comments

Comments
 (0)