Skip to content

Type narrowing of Any with is can widen type of variable for enum member to Any #21667

Description

@sirosen

Bug Report

Possibly related to #21364 and other union narrowing, although this occurs without a union.

When the following pattern is used to define a sentinel, strange "narrowing" behavior can occur:

class SentinelType(enum.Enum):
    SENTINEL = enum.auto()
SENTINEL: SentinelType = SentinelType.SENTINEL

If x: Any is narrowed by the comparison x is SENTINEL, mypy will start to treat SENTINEL as having type Any.

This does not happen if the namespaced enum member, SentinelType.SENTINEL is used. Only when a separate variable is used.

To Reproduce

https://mypy-play.net/?gist=174c92c83f84f44b2e8fefdcf5a0cd9b

import enum
import typing as t

class SentinelType(enum.Enum):
    SENTINEL = enum.auto()
SENTINEL: SentinelType = SentinelType.SENTINEL

x: t.Any = None
if x is SENTINEL:
    t.reveal_type(SENTINEL)

Expected Behavior

The type of SENTINEL should not be altered.

Actual Behavior

SENTINEL's revealed type is Any.

Your Environment

  • Mypy version used: 2.0, 2.1
  • Python version used: 3.10, 3.12, 3.14

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions