Mypy fails to infer enums being created from a list variable

Viewed 1000

Enums can be created by taking in a list of possible members, which I'm doing like so:

# example_issue.py
import enum

yummy_foods = ["ham", "cheese"]
foods = enum.Enum("Foods", yummy_foods)
cheese = foods.cheese

This looks OK, and runs fine, but mypy returns

example_issue.py:4: error: Enum() expects a string, tuple, list or dict literal as the second argument
example_issue.py:5: error: "Type[foods]" has no attribute "cheese"
Found 2 errors in 1 file (checked 1 source file)

What is mypy doing here, and why can't it follow that foods can take any value in yummy_foods?

1 Answers

Using a variable yummy_foods is too dynamic for mypy's static type checking, see this GitHub issue.

If you change your code to generate the Enum as:

foods = enum.Enum("Foods", ["ham", "cheese"])

mypy will then be able to figure out which attributes exist on the enumeration.

Related