Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm type hinting enum iteration

Python's enum class supports iteration, but PyCharm has trouble figuring this out.

from enum import Enum

class Color(Enum):
    RED = 0
    BLUE = 1

for color in Color:
    # Warning: Expected 'collections.Iterable', got 'Type[Color]' instead
    print(color)

Though the method EnumMeta.__iter__ exists, PyCharm has trouble figuring this out.

I don't mind manually adding type hinting to work around the problem, I'm just not sure what and where.

like image 274
Hetzroni Avatar asked Feb 05 '18 09:02

Hetzroni


1 Answers

Maybe it's not cleanest solution, but following works for me:

from enum import Enum
import typing

class Color(Enum):
    RED = 0
    BLUE = 1

Color = Color  # type: typing.Union[typing.Type[Color], typing.Iterable]

PyCharm supports type hinting using format defined in PEP 484 (for Python versions lower than 3.5 in the form of comments, for 3.5 and higher in form of annotations).

Important note here is that on Python version lower than 3.5, importing typing module should be guarded in some way (PyCharm recognizes this import as valid, even without having typing module installed in site packages, however when code is run ImportError occurs).

like image 152
bartem Avatar answered Oct 18 '22 16:10

bartem