-
For the following code snippet, from typing import TypeAlias, ClassVar, get_type_hints
ClassAlias: TypeAlias = ClassVar[str]
class A:
i: ClassAlias = "g" # No errors
class B:
i: ClassVar[str] = "g" # No errors
class A2(A):
i: ClassVar[str] = "g" # <<<<<<< pylance and mypy both flag this as an error
class B2(B):
i: ClassVar[str] = "g" # No errors
However, >>> print("type hints of A:", get_type_hints(A))
type hints of A: {'i': typing.ClassVar[str]}
>>> print("type hints of B:", get_type_hints(B))
type hints of B: {'i': typing.ClassVar[str]} I didn't pick up anything about a restricted scope of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The use of |
Beta Was this translation helpful? Give feedback.
ClassVar
should not be used outside of a variable declaration within a class.ClassVar
is not an annotation that describes the type of a variable, but it describes a (non-type) attribute of a variable. Most other languages offer keywords for such attributes, but Python overloads the type annotation mechanism to handle these cases. Other examples includeFinal
,InitVar
,Required
, andNotRequired
. These special forms should not be used within type aliases because they are not type annotations.The use of
ClassVar
should be flagged as an error when used in a type alias like this. When I implemented support for ClassVar in pyright, it never occurred to me that someone would attempt to use it …