2

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
2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.