mypy icon indicating copy to clipboard operation
mypy copied to clipboard

stubtest: reduce false-positive errors for attributes on enum members

Open AlexWaygood opened this issue 3 years ago • 0 comments

Description

The following pattern is fairly common for specialised enum classes that provide additional attributes on enum members. It's used for http.HTTPStatus in the stdlib, and in 3.11, it's also used for http.HTTPMethod:

from enum import IntEnum

class HTTPStatus(IntEnum):
    def __new__(cls, value, phrase, description=''):
        obj = int.__new__(cls, value)
        obj._value_ = value

        obj.phrase = phrase
        obj.description = description
        return obj

    CONTINUE = 100, 'Continue', 'Request received, please continue'
    SWITCHING_PROTOCOLS = 101, 'Switching Protocols', 'Switching to new protocol; obey Upgrade header'
    # etc.

The only reasonable way to write a stub for this is as follows:

from enum import IntEnum

class HTTPStatus(IntEnum):
    @property
    def phrase(self) -> str: ...
    @property
    def description(self) -> str: ...
    CONTINUE: int
    SWITCHING_PROTOCOLS: int

However, stubtest will emit false-positive errors on the phrase and description properties, since it can't find them on the enum class itself; they only exist on the enum members.

This PR teaches stubtest to look for properties on enum members if it can't find them on the enum class. Running stubtest on typeshed (on my Windows machine, with Python 3.10) with this patch applied, here is the additional output from stubtest, relative to the master branch:

+ note: unused allowlist entry http.HTTPStatus.description
+ note: unused allowlist entry http.HTTPStatus.phrase

If I were running on Python 3.11, I'm pretty sure the allowlist entry for http.HTTPMethod.description would also be flagged as unused.

Test Plan

I added a test.

AlexWaygood avatar Aug 04 '22 14:08 AlexWaygood