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.
Answer from Łukasz Rogalski on Stack OverflowPython 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.
Static Enforced Non generic Type alias?
Docstrings for new type aliases as defined in PEP 695 - Typing - Discussions on Python.org
Help understanding Type Aliases
Naming convention for type aliases
Videos
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?