Search code examples
pythonpython-typingtype-alias

Why doesn't Python's type checking raise an error when there is a mismatch with a TypeAlias?


Here's a trivial example:

"""Test typing problems."""

from typing import TypeAlias

Verb: TypeAlias = str


def concats_string(base: Verb) -> str:
    # Trivial example - should just append to the passed in value
    return " ".join([base, "World"])


greeting: str = "Hello"
print(concats_string(greeting))

I can't get MyPy, PyRight, or pytype to raise an error about the function call.
(Indeed, the join function should be flagged too...)

I'm guessing this is expected behaviour, since different implementations don't complain - but what am I missing here?

Isn't this the point of a TypeAlias and exactly what a type checker should flag?


Solution

  • It's the expected behaviour. As read in the documentation, the type alias "... will be treated equivalently by static type checkers".

    https://docs.python.org/3/library/typing.html#type-aliases

    The documentation is always a good starting point!