Since Python 3.10 it is possible to replace the Union
operator with |
.
old_style_type_hint: Union[int, float] = 5
new_style_type_hint: int|float = 5
I like the new syntax, however, I need to make sure that my code is running for Python 3.9, too. To ensure all functionalities, I can import annotations
like this:
from __future__ import annotations
However, this is only necessary if my Python version is <3.10.
Now, I am looking for some kind of conditional import, i.e. only import if I am using Python <3.10.
EDIT:
If I try a conditional import, I get an error.
import sys
if sys.version_info < (3, 10):
from __future__ import annotations
SyntaxError: from __future__ imports must occur at the beginning of the file