Skip to content
Merged
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
9 changes: 8 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -6746,7 +6746,14 @@ def narrow_type_by_identity_equality(
if i == j:
continue
# If we compare to a target with custom __eq__, we cannot narrow at all
or_if_maps.append({})
if is_overlapping_none(expr_type) and not is_overlapping_none(
operand_types[j]
):
# Narrow away from None. This is unsound, we're hoping that no one
# has a custom __eq__ that returns True for None.
or_if_maps.append({operands[i]: remove_optional(expr_type)})
else:
or_if_maps.append({operands[i]: expr_type})
continue
target_type = operand_types[j]
if should_coerce_literals:
Expand Down
3 changes: 3 additions & 0 deletions mypy/types_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
TypeAliasType,
TypeType,
TypeVarType,
UninhabitedType,
UnionType,
UnpackType,
flatten_nested_unions,
Expand Down Expand Up @@ -134,6 +135,8 @@ def remove_optional(typ: Type) -> Type:
return UnionType.make_union(
[t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]
)
elif isinstance(typ, NoneType):
return UninhabitedType()
else:
return typ

Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,22 @@ def f(x: Custom | None, y: int | None):
[case testNarrowingCustomEqualityUnion4]
# flags: --strict-equality --warn-unreachable
from __future__ import annotations

class Custom:
def __eq__(self, other: object) -> bool:
return True

def f(x: Custom | None, y: Custom):
if x == y:
# We unsoundly special case None and narrow x to Custom here
reveal_type(x) # N: Revealed type is "__main__.Custom"
else:
reveal_type(x) # N: Revealed type is "__main__.Custom | None"
[builtins fixtures/primitives.pyi]

[case testNarrowingCustomEqualityUnion5]
# flags: --strict-equality --warn-unreachable
from __future__ import annotations
from typing import Any

class Custom1:
Expand Down