KEMBAR78
stubtest: Fallback to `getattr_static` if an attribute can't be found on a class at runtime by AlexWaygood · Pull Request #13285 · python/mypy · GitHub
Skip to content

Conversation

AlexWaygood
Copy link
Member

@AlexWaygood AlexWaygood commented Jul 29, 2022

Description

Stubtest currently emits false-positive errors on most of the stdlib enums in typeshed, due to this behaviour:

>>> from enum import Enum
>>> class Foo(Enum):
...     BAR = 1
...
>>> Foo.BAR.value
1
>>> Foo.BAR.value = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\alexw\AppData\Local\Programs\Python\Python310\lib\types.py", line 187, in __set__
    raise AttributeError("can't set attribute")
AttributeError: can't set attribute
>>> Foo.value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\alexw\AppData\Local\Programs\Python\Python310\lib\enum.py", line 437, in __getattr__
    raise AttributeError(name) from None
AttributeError: value

The value property exists on enum classes, but stubtest can't see it due to some magic the enum module does to make value raise an AttributeError if you try to access it on the class itself, rather than on an enum member. We can avoid these false-positive errors by falling back to getattr_static if the attribute can't be found using getattr.

Output from running typeshed's stubtest_stdlib.py, with this patch checked out, relative to running the same test with mypy master checked out:

+ note: unused allowlist entry enum.Enum.name
+ note: unused allowlist entry enum.Enum.value
+ note: unused allowlist entry enum.Flag.name
+ note: unused allowlist entry enum.Flag.value
+ note: unused allowlist entry enum.IntEnum.value

Test Plan

I added a test.

Copy link
Collaborator

@hauntsaninja hauntsaninja left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@hauntsaninja hauntsaninja merged commit 5e340c1 into python:master Jul 29, 2022
@AlexWaygood AlexWaygood deleted the stubtest-classproperties branch July 29, 2022 19:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants