Skip to content

Inconsistent assignability of enum literal unions vs enum #18896

@sterliakov

Description

@sterliakov

Bug Report

Enum should be assignable to union of its literals (expansion). Mypy usually understands that, but not when union is behind an alias.

To Reproduce

playground

from enum import Enum
from typing import Literal

class E(Enum):
    A = 'a'
    B = 'b'
    C = 'c'
    
A = Literal[E.A]
B = Literal[E.B, E.C]

def f(x: A | B) -> None: ...
def f2(x: A | Literal[E.B, E.C]) -> None: ...
def f3(x: Literal[E.A] | B) -> None: ...

def main(x: E) -> None:
    f(x)  # E: Argument 1 to "f" has incompatible type "E"; expected "Literal[E.A] | Literal[E.B, E.C]"  [arg-type]
    f2(x)
    f3(x)  # E: Argument 1 to "f" has incompatible type "E"; expected "Literal[E.A] | Literal[E.B, E.C]"  [arg-type]

Expected Behavior

Success, 0 errors.

Actual Behavior

main.py:17: error: Argument 1 to "f" has incompatible type "E"; expected "Literal[E.A] | Literal[E.B, E.C]"  [arg-type]
main.py:19: error: Argument 1 to "f3" has incompatible type "E"; expected "Literal[E.A] | Literal[E.B, E.C]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.15.0 and master
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12

I have a patch for this - just a small impl omission. Discovered while looking at #18895.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions