0

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
Andi
  • 3,196
  • 2
  • 24
  • 44
  • check https://stackoverflow.com/questions/1093322/how-do-i-check-which-version-of-python-is-running-my-script – Noelkd Sep 28 '22 at 10:31
  • Just because it isn't necessary, doesn't mean it is invalid or causes an error. If your application should only support Python `3.10+`, omit the line. Otherwise, keep it. – Daniil Fajnberg Sep 28 '22 at 12:22

0 Answers0