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 include Final, InitVar, Required, and NotRequired. 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 in a type alias, so there is no check for this error condition. But you should assume that it will not work when used in this manner.
Hi
Im reading through the typing documentation https://docs.python.org/3/library/typing.html and have a question that I cannot answer.
In the past when I wanted to use type aliases I would use code like Vector = list[float] (I think that I must have picked this up from a post on stack overflow or something).
However, in the document above it suggests using the code type Vector = list[float].
The difference between the two is that the data type is types.GenericAlias (the list[float]) for the first Vector and typing.TypeAliasType for the second Vector.
But besides that I am not really sure what is the difference between these two methods. Im not sure where the reason to use one over the other is. Im also not sure where the documntation is for the first example (maybe technically this is not a Type Alias).
Im not sure if anyone can help here?
Python 3.5+
Since Python 3.5 you may use typing module.
Quoting docs, A type alias is defined by assigning the type to the alias:
Copy# Python 3.5-3.8
from typing import List
Vector = List[float]
# Python 3.9+
Vector = list[float] # No import needed, lower case l
To learn more about enforcing types in Python you may want to get familiar with PEPs: PEP483 and PEP484.
Python historically was using duck-typing instead of strong typing and hadn't built-in way of declaring types before 3.5 release.
Python 3.10+
Since Python 3.10, the TypeAlias annotation is available in the typing module.
It is used to explicitly indicate that the assignment is done to generate a type alias. For example:
CopyPoint: TypeAlias = tuple[float, float]
Triangle: TypeAlias = tuple[Point, Point, Point]
You can read more about the TypeAlias annotation on the PEP 613 that introduced it.