Skip to content

Commit 95e448b

Browse files
committed
Fix custom equality handling for membership narrowing in static containers
This was an issue in the new feature #21461 In narrow_type_by_identity_equality we check for custom equality before coercing to literals, and this was done the wrong way round here Fixes #21703
1 parent b6d93f5 commit 95e448b

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

mypy/checker.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6858,9 +6858,13 @@ def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMa
68586858
for known_item in container_item_types:
68596859
# Match the should_coerce_literals logic from narrow_type_by_identity_equality
68606860
p_known_item = get_proper_type(known_item)
6861-
if is_literal_type_like(p_known_item) or (
6862-
isinstance(p_known_item, Instance) and p_known_item.type.is_enum
6863-
):
6861+
if (
6862+
is_literal_type_like(p_known_item)
6863+
or (
6864+
isinstance(p_known_item, Instance)
6865+
and p_known_item.type.is_enum
6866+
)
6867+
) and not has_custom_eq_checks(p_known_item):
68646868
known_item = coerce_to_literal(known_item)
68656869
if_map, else_map = self.narrow_type_by_identity_equality(
68666870
"==",

test-data/unit/check-narrowing.test

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3335,6 +3335,24 @@ def narrow_dict(x: Literal['a', 'b', 'c'], t: dict[Literal['a', 'b'], int]):
33353335
[builtins fixtures/primitives.pyi]
33363336

33373337

3338+
[case testNarrowCustomEqEnumInLiteralContainer]
3339+
# flags: --strict-equality --warn-unreachable
3340+
# https://github.com/python/mypy/issues/21703
3341+
from enum import Enum
3342+
3343+
class E(Enum):
3344+
foo = 1
3345+
bar = 2
3346+
3347+
def __eq__(self, other: object) -> bool:
3348+
return True
3349+
3350+
def f(x: int) -> None:
3351+
if x in [E.foo, E.bar]:
3352+
reveal_type(x) # N: Revealed type is "builtins.int"
3353+
[builtins fixtures/list.pyi]
3354+
3355+
33383356
[case testNarrowingLiteralInLiteralContainer]
33393357
# flags: --strict-equality --warn-unreachable
33403358
from typing import Literal

0 commit comments

Comments
 (0)