Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Incorrect deduplication of Enum values in Union[Literal[1], Literal[SomeEnum.one]] #103592

Closed
@adriangb

Description

@adriangb

This was fixed on 3.9 (by #23294 or followups). Here's a test / example:

from enum import Enum
from typing import Literal, Union, get_args


class MyEnum(int, Enum):
    foo = 1

tp = Union[Literal[MyEnum.foo], Literal[1]]
assert len(get_args(tp)) == 2, get_args(tp)

tp = Union[Literal[1], Literal[MyEnum.foo]]
assert len(get_args(tp)) == 2, get_args(tp)

These assertions fail on 3.8 since Union deduplicates both Literals into the same thing. The reason you need Literal here is because enum values are values not types so they can only appear in a Union if they're also within a Literal.

As per #23294 (comment) maybe the answer here is to not do anything. And in fact I looked into back porting and it was too big of a change to be called a back port. But I didn't see this specific issue w/ Enum and Union reported, so I at least wanted to report it and confirm that it is a bug.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions