Search code examples
pythonaliastype-hintingpython-typing

How do you alias a type in Python?


In some (mostly functional) languages you can do something like this:

type row = list(datum)

or

type row = [datum]

So that we can build things like this:

type row = [datum]
type table = [row]
type database = [table]

Is there a way to do this in Python? You could do it using classes, but Python has quite some functional aspects so I was wondering if it could be done an easier way.


Solution

  • 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:

    Point: 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.