Skip to content

Incorrect narrowing of Enum.Flag #21937

Description

@zedzhen

Bug Report

Incorrect narrowing of Enum.Flag

To Reproduce

from enum import Flag, auto
from pathlib import Path
from tempfile import NamedTemporaryFile


def p1(path: str) -> None: ...
def p2(path: str) -> None: ...
def p2_fast(data: str) -> str: ... # type: ignore[empty-body]
def p3(path: str) -> None: ...


class Programs(Flag):
    NONE = 0
    P1 = auto()
    P2 = auto()
    P3 = auto()
    ALL = P1 | P2 | P3


def f(data: str, programs: Programs) -> str:
    if programs == Programs.NONE:
        return data
    if programs == Programs.P2:
        return p2_fast(data)
    with NamedTemporaryFile("w", encoding="utf-8", delete=False) as tmp:
        tmp.write(data)
        tmp.close()
        if Programs.P1 in programs:
            p1(tmp.name)
        if Programs.P3 in programs:
            p3(tmp.name)
        if Programs.P2 in programs:
            p2(tmp.name)
        return Path(tmp.name).read_text("utf-8")

Expected Behavior

no warning

Actual Behavior

main.py:32: error: Unsupported operand types for in ("Programs" and "Literal[Programs.P1, Programs.P3, Programs.ALL]") [operator]

Your Environment

  • Mypy version used: 2.3.1
  • Mypy command-line flags: no
  • Mypy configuration options from mypy.ini (and other config files): no
  • Python version used: 3.14

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions