pythonpython-typingmypytype-alias

mypy: Is it possible to define a shortcut for complex type?


I am using Python3 and have just learned how to use mypy. I was reading the documentation (espcially this part seemed relevant), but couldn't find any answers to my question:

Is is possible to define some shortcuts for types?

Example:

Rather than writing

from typing import List


def f(x: List[int]) -> List[int]:
    return x[1:]

I would like to have

from typing import List

sequence = DefineTypeShortcut(List[int])

def f(x: sequence) -> sequence:
    return x[1:]

Just to clarify, I do not want to define a new class Sequence, I just want more easily readable signatures of functions.


Solution

  • Yes, you're looking for type aliases. Fortunately they are pretty straight forward, by assigning to a new name the name can act as a hint for the type.

    The example supplied in the docs provides an example of exactly the thing you're after:

    from typing import List
    Vector = List[float]
    
    def scale(scalar: float, vector: Vector) -> Vector:
        return [scalar * num for num in vector]