How to define type which could differ due to ImportError #4160
-
I have code which imports an Enum but that import might not be available, so a try/except ImportError is setup. Pyright gives an error that the types are not the same; i believe since the type is assumed to be from the first declaration. Question Context Example Code from enum import IntEnum
try:
from http import HTTPStatus
except ImportError:
class HTTPStatus(IntEnum):
NOT_FOUND = 404
def get_status_code_as_str(status: HTTPStatus) -> str:
return str(status.value) Error /private/tmp/test/ht.py
/private/tmp/test/ht.py:4:22 - error: Expression of type "Type[HTTPStatus]" cannot be assigned to declared type "Type[HTTPStatus]"
"http.HTTPStatus" is incompatible with "ht.HTTPStatus"
Type "Type[HTTPStatus]" cannot be assigned to type "Type[HTTPStatus]" (reportGeneralTypeIssues) Some things I tried HTTPStatus = type('HTTPStatus', (IntEnum,), {"NOT_FOUND": 404}) But I believe that is just working around the typechecker. I also thought I could create a typealias by renaming the enums, i.e. if TYPE_CHECKING:
HTTPStatus: TypeAlias = HTTPStatusImport | HTTPStatusRedefined But the typechecker correctly tells me that HTTPStatusImport is unbound. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 import sys
if sys.version_info >= (3, 11):
from http import HTTPStatus
else:
from enum import IntEnum
class HTTPStatus(IntEnum):
NOT_FOUND = 404 |
Beta Was this translation helpful? Give feedback.
I recommend against attempting to create a union. Stick to one type or the other and use that for static type checking.
Or you could use a conditional check based on
sys.version
: