Pylance-release: Pylance only expects enum item string as second parameter

Created on 14 Jul 2020  路  3Comments  路  Source: microsoft/pylance-release

Environment data

  • Language Server version: Pylance language server 2020.7.1
  • OS and version: Windows 10 64bit
  • Python version: 3.8.2

Expected behaviour

No error message and maybe even type hints about which kind of arguments enum.Enum can take.
See the docs.

names: The Enum members. This can be a whitespace or comma separated string (values will start at 1 unless otherwise specified):

'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'
or an iterator of names:

['RED', 'GREEN', 'BLUE']
or an iterator of (name, value) pairs:

[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]
or a mapping:

{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}

Actual behaviour

Message Expected enum item string as second parameter while code below is working as intended.

Code Snippet / Additional information

import enum
x = {"a":1, "b":2}

Thing = enum.Enum("Name", x.items()) # pylance marks error: Expected enum item string as second parameter
print(Thing.a.value) # prints 1
bug fixed in next version

All 3 comments

Thanks for the bug report.

If you pass a dynamic expression as the second argument to Enum() (as you have done in the code above), the type checker will have no knowledge of the enumerated values. You won't receive any completion suggestions, and Pylance won't be able to detect and report any incorrect usage. So, of the half dozen different ways to specify an enum in Python, I strongly recommend using the more standard class declaration rather than the forms you mentioned above.

class Name(Enum):
   a = 1
   b = 2

I think it's worth keeping the error in place but making it conditional on the reportGeneralTypeErrors rule. That way, it won't appear if you have typeCheckingMode set to "off". If you are interested in type checking, then it's important to know that switching to the more standard syntax for Enums will provide better results.

This change will be included in the next version of Pylance / Pyright.

This issue has been fixed in version 2020.7.2, which we've just released. You can find the changelog here: https://github.com/microsoft/pylance-release/blob/master/CHANGELOG.md#202072-15-july-2020

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BrunoBlanes picture BrunoBlanes  路  4Comments

albireox picture albireox  路  5Comments

eddyg picture eddyg  路  3Comments

savannahostrowski picture savannahostrowski  路  4Comments

martinjohndyer picture martinjohndyer  路  4Comments