In Python documentation for typing & type hints we have the below example:
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
Vector type alias clearly shows that type aliases are useful for simplifying complex type signatures.
However, what about aliasing primitive data types?
Let's contrast two basic examples of function signatures:
URL = str
def process_url(url: URL) -> URL:
pass
vs.
def process_url(url: str) -> str:
pass
Version with type alias URL for primitive type str is:
- self-documenting (among others, now I can skip documenting returned value, as it should be clearly an url),
- resistant to type implementation change (I can switch URL to be
Dictornamedtuplelater on without changing functions signatures).
The problem is I cannot find anyone else following such practice. I am simply afraid that I am unintentionally abusing type hints to implement my own ideas instead of following their intended purpose.
Note from 2020-10
Python 3.9 introduces "flexible function and variable annotations", which allows to make annotations like:
def speed_1(distance: "feet", time: "seconds") -> "miles per hour":
pass
def speed_2(
distance: Annotated[float, "feet"], time: Annotated[float, "seconds"]
) -> Annotated[float, "miles per hour"]:
pass
Which renders aliasing data types for documenting purposes rather redundant!
See:
URLtype, then you can simply change it, and all type checking will change. In Python, I occasionally see a class that is defined with two identifiers. - Willem Van Onsemprocess_urlwill be the same in either case! Only the source code shows the alias; any usage has no idea which name was used to refer to the basic type. Even in the first case, the actual signature is justprocess_url(url: str) -> str. - MisterMiyagi