用于抽象Enum值的python类型注释

时间:2020-05-06 12:43:23

标签: python enums typing

我有一个枚举

from enum import Enum

class StrangeEventTypeVariants(Enum):
    crew_training = "Crew training"
    crew_travel = "Crew travel"
    flight = "Flight"
    maintenance = "Maintenance"
    parking = "Parking"

并具有处理抽象枚举的类的功能

class EnumSuggest:
    def __init__(self, enum: Enum):
        self.variants = [{"id": member.name, "name": member.value} for member in enum]

    def get_suggest(self, _):
        return self.variants

但是上面的注释不正确,对于

suggest = EnumSuggest(StrangeEventTypeVariants)

我收到了下一个棉绒警告

预期类型为Enum,类型为[StrangeEventTypeVariants]

如何修复?

1 个答案:

答案 0 :(得分:0)

您没有将Enum实例传递给EnumSuggest.__init__;您正在传递Enum子类。类型提示应该反映出这一点。

class EnumSuggest:
    def __init__(self, enum: Type[Enum]):
        self.variants = [{"id": member.name, "name": member.value} for member in enum]

    def get_suggest(self, _):
        return self.variants