Pyright: `Literal` `enum.Enum` value not allowed

Created on 4 May 2020  路  2Comments  路  Source: microsoft/pyright

Describe the bug

Literals in pyright can be used for str, int, None, bytes and bool values as expected, but pyright's handling of Literal does not accept an enum.Enum value as it should.

To Reproduce

Create an eum & attempt to use it in a type as follows:

class SomeEnum(Enum):
    SOME_ENUM_VALUE = 'beep'

class SomeTypedDictionary(TypedDict):
    value: Literal[SomeEnum.SOME_ENUM_VALUE]

Note that SomeEnum.SOME_ENUM_VALUE is squiggled & a message is displayed indicating that an enum value is not acceptable.

You'll see that

Expected behavior

A literal having an enum.Enum value should be accepted as a valid type per PEP-586 (see https://www.python.org/dev/peps/pep-0586/#id24).

Screenshots or Code

image

VS Code extension or command-line

Pyright 1.1.35 is running as a VSCode extension.

addressed in next version bug

All 2 comments

Thanks for the bug report. This support will be in the next release of Pyright.

I've not only added support for enum literals, I've also added type narrowing support for comparisons to enum literals.

For example:

class SomeEnum(Enum):
   VALUE1 = 1
   VALUE2 = 2
   VALUE3 = 3

def func1(a: SomeEnum):
if a == SomeEnum.VALUE1:
    # We know a must be VALUE1
    reveal_type(a)
 else:
    # We know a must be either VALUE2 or VALUE3
    reveal_type(a)

Before this change, the two calls to reveal_type would have both output SomeEnum. Now, the first one outputs Literal[SomeEnum.VALUE1] and the second outputs Literal[SomeEnum.VALUE2, SomeEnum.Value3].

This is now fixed in version 1.1.36, which I just published.

Was this page helpful?
0 / 5 - 0 ratings