python / python/mypy

Type mismatch error with overlapping enums

Open
#15,196 0 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Enum is casted to literal when asserting its value, even when it is declared as attr of class that can be mutated after assertion

To Reproduce

from enum import Enum


class MyEnum(Enum):
    A = 1
    B = 2


class A:
    def __init__(self, enum: MyEnum):
        self.enum = enum

    def change(self) -> None:
        self.enum = MyEnum.B

if __name__ == "__main__":
    a = A(MyEnum.A)
    assert a.enum == MyEnum.A
    a.change()
    assert a.enum == MyEnum.B  

Expected Behavior

No error

Actual Behavior

Non-overlapping equality check (left operand type: "Literal[MyEnum.A]", right operand type: "Literal[MyEnum.B]")

Your Environment

  • Mypy version used: current master
  • Mypy command-line flags: --strict
  • Python version used: 3.10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided example with mypy --strict on Python 3.10 and inspect how enum equality assertions narrow attributes that can be mutated. Trace the handling of attribute narrowing and enum literals, then add coverage for this reproduction. Done means the example produces no erroneous non-overlapping equality error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.