Skip to content Skip to sidebar Skip to footer

Why Is Mypy Complaining About List Comprehension When It Can't Be Annotated?

Why does Mypy complain that it requires a type annotation for a list comprehension variable, when it is impossible to annotate such a variable using MyPy? Specifically, how can I r

Solution 1:

In a list comprehension, the iterator must be cast instead of the elements.

from typing import Iterable, cast
from enum import EnumMeta, Enum

defspam(y: EnumMeta):
    return [[x.value] for x in cast(Iterable[Enum], y)]

This allows mypy to infer the type of x as well. In addition, at runtime it performs only 1 cast instead of n casts.

If spam can digest any iterable that produces enums, it is easier to type hint this directly.

from typing import Iterable
from enum import Enum

defspam(y: Iterable[Enum]):
    return [[x.value] for x in y]

Solution 2:

MisterMyagi's answer is the best solution for this specific case. It may be worth noting, however, that it is also possible to declare the type of a variable before that variable is defined. The following also passes MyPy:

from enum import Enum

defspam(y: type[Enum]):
    x: Enum
    return [[x.value] for x in y]

Post a Comment for "Why Is Mypy Complaining About List Comprehension When It Can't Be Annotated?"