Proper type hint for IntEnum attribute of dataclass?

Viewed 581

I'm creating a dataclass in 3.8.8 to store result from REST API call, and one of its attributes is used to store HTTP response status:

from dataclasses import dataclass
from http import HTTPStatus


@dataclass
class APICallResult:
    response_text: str
    http_status: HTTPStatus

When I try to create an object of this class as below:

result = APICallResult('foo', HTTPStatus.OK)

PyCharm 2020.3.3 just flags HTTPStatus.OK with error:

Expected type 'HTTPStatus', got 'int' instead`.

Now I wonder what's the proper type hint for IntEnum in this case? I think Literal might be an awkward option here.

1 Answers

HTTPStatus.OK is a member of the HTTPStatus IntEnum subclass:

class http.HTTPStatus

A subclass of enum.IntEnum that defines a set of HTTP status codes, reason phrases and long descriptions written in English.

The error you are getting is bug in the PyCharm static type checker, if you write the attribute type hint like in the example below and test it with mypy you'll see there is no error:

from dataclasses import dataclass
from http import HTTPStatus
from typing import Literal


@dataclass
class APICallResult:
    response_text: str
    http_status: Literal[HTTPStatus.OK]


result = APICallResult('foo', HTTPStatus.OK)

mypy issues no warning

Success: no issues found in 1 source file

If you try to annotate the dataclass attribute like this:

from dataclasses import dataclass
from http import HTTPStatus


@dataclass
class APICallResult:
    response_text: str
    http_status: HTTPStatus.OK


result = APICallResult('foo', HTTPStatus.OK)

mypy gives the following warning:

main.py:9: error: Invalid type: try using Literal[HTTPStatus.OK] instead?
Found 1 error in 1 file (checked 1 source file)

The rules for annotating a Enum member are given in PEP 586 -- Literal Types:

Legal parameters for Literal at type check time

Literal[Color.RED] # Assuming Color is some enum

Related