-
Code sample in pyright playground from typing import Generic, TypeVar
T = TypeVar("T")
class Model(Generic[T]):
t: T
Sub = Model[T][int] Although this is fine at runtime, pyright emits a "Type "Model[T@Sub]" is already specialized" error when defining This doesn't happen when doing it in two steps: Sub = Model[T]
Sub2 = Sub[int] Is this expected behavior? Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Answered by
erictraut
Aug 30, 2024
Replies: 1 comment 3 replies
-
This is expected behavior. You cannot specialize a class twice. I'm not even sure what this would mean. The fact that this does not crash at runtime does not make it valid. Perhaps your intent is to define a generic type alias? type Sub[T] = Model[T]
Sub2 = Sub[int] |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The statement
Sub = Model[T]
is the old-style (PEP 484) way to define a generic type alias. It's equivalent to the less-old-styleSub: TypeAlias = Model[T]
or the moderntype Sub[T] = Model[T]
.Once a generic type alias is defined, you can specialize it using subscripts.
In your first code snippet, you're not defining a type alias, and
Model[T][int]
has no valid meaning to a type checker. For the same reason,A[int, list[S]][str]
is invalid.