[Python] Type hints: Is it a bad practice to alias primitive data types?

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    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 Dict or namedtuple later 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:


    Continue reading...

Compartilhe esta Página