Skip to content

Enum type not assignable to complete union of its literal members #11169

@ericmarkmartin

Description

@ericmarkmartin

Describe the bug
According to the typing spec for enums,

a type checker should treat a complete union of all literal members as equivalent to the enum type, but not from the enum type to the union.

However, Pyright currently only allows assignment from the union to the enum type, but not from the enum type to the union.

Code or Screenshots

from enum import Enum
from typing import Literal

class Color(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

def contraction_id(c: Literal[Color.RED, Color.GREEN, Color.BLUE]) -> Color:
    return c

def expansion_id(c: Color) -> Literal[Color.RED, Color.GREEN, Color.BLUE]:
    return c

The error reported is

Type "Color" is not assignable to return type "Literal[Color.RED, Color.GREEN, Color.BLUE]"
  Type "Color" is not assignable to type "Literal[Color.RED, Color.GREEN, Color.BLUE]"
    "Color" is not assignable to type "Literal[Color.RED]"
    "Color" is not assignable to type "Literal[Color.GREEN]"
    "Color" is not assignable to type "Literal[Color.BLUE]"  (reportReturnType)

VS Code extension or command-line

Pyright playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions