Incorrect narrowing of Enum.Flag
Open
Nobody has claimed this yet.
bug
topic-enum
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the reported Enum.Flag narrowing example with the supplied Python snippet and mypy configuration. Trace the narrowing performed after comparisons with Programs.NONE and Programs.P2, then add a regression test for membership checks such as Programs.P1 in programs. Done means the example produces no unsupported-operand warning.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 65/100