Skip to content

Fix Enum.value inference for Enums with @cached methods #19374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 2 additions & 13 deletions mypy/plugins/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,22 +196,11 @@ class SomeEnum:
if _implements_new(info):
return ctx.default_attr_type

stnodes = (info.get(name) for name in info.names)

# Enums _can_ have methods, instance attributes, and `nonmember`s.
# Omit methods and attributes created by assigning to self.*
# for our value inference.
node_types = (
get_proper_type(n.type) if n else None
for n in stnodes
if n is None or not n.implicit
)
proper_types = [
_infer_value_type_with_auto_fallback(ctx, t)
for t in node_types
if t is None
or (not isinstance(t, CallableType) and not is_named_instance(t, "enum.nonmember"))
]
node_types = (get_proper_type(info[name].type) for name in info.enum_members)
proper_types = [_infer_value_type_with_auto_fallback(ctx, t) for t in node_types]
underlying_type = _first(proper_types)
if underlying_type is None:
return ctx.default_attr_type
Expand Down
25 changes: 25 additions & 0 deletions test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -2635,3 +2635,28 @@ reveal_type(Wrapper.Nested.FOO) # N: Revealed type is "Literal[__main__.Wrapper
reveal_type(Wrapper.Nested.FOO.value) # N: Revealed type is "builtins.ellipsis"
reveal_type(Wrapper.Nested.FOO._value_) # N: Revealed type is "builtins.ellipsis"
[builtins fixtures/enum.pyi]

[case testValueFallbackWithCachedMethod]
from enum import Enum, auto
from collections.abc import Hashable
from typing import Callable, Generic, TypeVar

_T = TypeVar("_T")

class _lru_cache_wrapper(Generic[_T]):
def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ...

def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ...

class Color(Enum):
RED = auto()

@cache
def lowercase_name(self) -> str:
return self.name

reveal_type(Color.RED.value) # N: Revealed type is "builtins.int"

def frobnicate(color: Color) -> None:
reveal_type(color.value) # N: Revealed type is "builtins.int"
[builtins fixtures/primitives.pyi]