TIL - Importing annotations from future for concise Python typing

Posted on Fri 18 March 2022 in Dispatches • 1 min read

Python 3.10 introduced several improvements for type hints, including a much more concise Union operator. This means that instead of using:

def square(number: Union[int, float]) -> Union[int, float]:
    return number ** 2

You can instead write this:

def square(number: int | float) -> int | float:
    return number ** 2

The examples above can be found in the Python 3.10 release notes.

I already knew about these changes, but what I didn’t know is that you can make use of these same improvements in your code as early as Python 3.7 if you do the following.

from __future__ import annotations

Thanks to Will McGugan for pointing this out on Twitter!