Skip to content
Draft
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
7 changes: 7 additions & 0 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,13 @@ def analyze_class_attribute_access(
return itype.extra_attrs.attrs[name]
if info.fallback_to_any or info.meta_fallback_to_any:
return apply_class_attr_hook(mx, hook, AnyType(TypeOfAny.special_form))
# For enum types, report missing member with fuzzy matching suggestions
if (
info.is_enum
and info.enum_members
and not (name.startswith("__") and name.endswith("__"))
):
return report_missing_attribute(mx.original_type, itype, name, mx)
return None

if (
Expand Down
17 changes: 17 additions & 0 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,23 @@ def has_no_attr(
code=codes.ATTR_DEFINED,
)
failed = True
elif isinstance(typ, Instance) and typ.type.names:
alternatives = set(typ.type.names.keys())
alternatives.discard(member)
matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives]
matches.extend(best_matches(member, alternatives, n=3))
if matches:
self.fail(
'{} has no attribute "{}"; maybe {}?{}'.format(
format_type(original_type, self.options),
member,
pretty_seq(matches, "or"),
extra,
),
context,
code=codes.ATTR_DEFINED,
)
failed = True
if not failed:
self.fail(
'{} has no attribute "{}"{}'.format(
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -2550,6 +2550,20 @@ class Pet(Enum):
# E: Incompatible types in assignment (expression has type "ellipsis", variable has type "str")
[builtins fixtures/enum.pyi]

[case testEnumMemberFuzzyMatch]
from enum import Enum

class Color(Enum):
GREEN = 1
RED = 2
YELLOW = 3

Color.GREN # E: "type[Color]" has no attribute "GREN"; maybe "GREEN"?
Color.YELOW # E: "type[Color]" has no attribute "YELOW"; maybe "YELLOW"?
Color.RDE # E: "type[Color]" has no attribute "RDE"
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This doesn't trigger fuzzy matching due to it being below the 0.75 threshold in best_matches

Color.BLUE # E: "type[Color]" has no attribute "BLUE"
[builtins fixtures/enum.pyi]

[case testEnumValueWithPlaceholderNodeType]
# https://github.com/python/mypy/issues/11971
from enum import Enum
Expand Down