Skip to content

How to define type which could differ due to ImportError #4160

Answered by erictraut
BrandonNav asked this question in Q&A
Discussion options

You must be logged in to vote

I recommend against attempting to create a union. Stick to one type or the other and use that for static type checking.

from enum import IntEnum
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    class HTTPStatus(IntEnum):
        NOT_FOUND = 404
else:
    try:
        from http import HTTPStatus
    except ImportError:
        class HTTPStatus(IntEnum):
            NOT_FOUND = 404

Or you could use a conditional check based on sys.version:

import sys

if sys.version_info >= (3, 11):
    from http import HTTPStatus        
else:
    from enum import IntEnum
    class HTTPStatus(IntEnum):
        NOT_FOUND = 404

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@BrandonNav
Comment options

Answer selected by BrandonNav
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants