简体   繁体   English

PyCharm 类型提示枚举迭代

[英]PyCharm type hinting enum iteration

Python's enum class supports iteration, but PyCharm has trouble figuring this out. Python 的 enum 类支持迭代,但 PyCharm 无法解决这个问题。

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.尽管EnumMeta.__iter__方法存在,但 PyCharm EnumMeta.__iter__这个问题。

I don't mind manually adding type hinting to work around the problem, I'm just not sure what and where.我不介意手动添加类型提示来解决这个问题,我只是不确定是什么以及在哪里。

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). PyCharm 支持使用PEP 484 中定义的格式进行类型提示(对于低于 3.5 的 Python 版本以注释形式,对于 3.5 及更高版本以注释形式)。

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).这里重要的一点是,在低于 3.5 的 Python 版本上,应该以某种方式保护导入typing模块(PyCharm 识别此导入是有效的,即使没有在站点包中安装typing模块,但是当代码运行时,会发生ImportError )。

A workaround that I used in PyCharm was through use of __members__ with .items()我在 PyCharm 中使用的一种解决方法是使用__members__.items()

from enum import Enum

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

for name, color in Color.__members__.items():
    print(name, color)

Returning:返回:

('RED', <Color.RED: 0>)
('BLUE', <Color.BLUE: 1>)

See the following link for reference:请参阅以下链接以供参考:

https://cpython-test-docs.readthedocs.io/en/latest/library/enum.html#iteration https://cpython-test-docs.readthedocs.io/en/latest/library/enum.html#iteration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM