From 2d407519802722a3ec396231413e0bffa912d7ee Mon Sep 17 00:00:00 2001 From: dannyward630 Date: Sun, 5 Jul 2026 09:07:33 +0200 Subject: [PATCH] Fix Any identity narrowing of enum sentinels --- mypy/checker.py | 4 ++++ test-data/unit/check-enum.test | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/mypy/checker.py b/mypy/checker.py index d13b927b28f2f..5dd78b6e54b6c 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -7019,6 +7019,10 @@ def narrow_type_by_identity_equality( target_type = operand_types[j] if should_coerce_literals: target_type = coerce_to_literal(target_type) + if isinstance(get_proper_type(target_type), AnyType) and not isinstance( + get_proper_type(expr_type), AnyType + ): + continue # Morally what we want to do is narrow for each branch based on: # `if_type, else_type = conditional_types(expr_type, target)` diff --git a/test-data/unit/check-enum.test b/test-data/unit/check-enum.test index 20cf3b5aebfbc..d05e4fedc9efb 100644 --- a/test-data/unit/check-enum.test +++ b/test-data/unit/check-enum.test @@ -2983,3 +2983,19 @@ def f(x: SE | None) -> None: else: reveal_type(x) # N: Revealed type is "__main__.SE | None" [builtins fixtures/primitives.pyi] + + +[case testEnumSentinelComparedToAny] +import enum +from typing import Any + +class SentinelType(enum.Enum): + SENTINEL = enum.auto() + +SENTINEL: SentinelType = SentinelType.SENTINEL + +x: Any = None +if x is SENTINEL: + reveal_type(x) # N: Revealed type is "Literal[__main__.SentinelType.SENTINEL]" + reveal_type(SENTINEL) # N: Revealed type is "__main__.SentinelType" +[builtins fixtures/primitives.pyi]