Skip to content

Inconsistent assignability of enum literal unions vs enum #18896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sterliakov opened this issue Apr 7, 2025 · 0 comments · Fixed by #18898
Closed

Inconsistent assignability of enum literal unions vs enum #18896

sterliakov opened this issue Apr 7, 2025 · 0 comments · Fixed by #18898
Assignees
Labels
bug mypy got something wrong topic-enum

Comments

@sterliakov
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-enum
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant