我有这种只对相关数据进行分组的数据类型。它应该是一个类似结构的东西,所以我选择了一个namedtuple.ConfigOption = namedtuple('ConfigOption', 'one two animal vehicle fairytale')另一方面,namedtuple没有默认值,所以我驻留在另一个答案中提出的黑客。ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella")显然,这会使类型检查失败: error: "Callable[[Type[NT], Any, Any, Any, Any, Any], NT]" has no attribute "__defaults__"因为我很清楚这是一个 hack,所以我使用内联注释告诉类型检查器# type: disable:ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella") # type: disable这时候……队伍变得太长了。我不知道如何打破这一行,使其在语法上正确,同时让类型检查器跳过它:# the ignore is on the wrong lineConfigOption.__new__.__defaults__ = \ (1, 2, "White Horse", "Pumpkin", "Cinderella") # type: ignore# unexpected indentationConfigOption.__new__.__defaults__ = # type: ignore (1, 2, "White Horse", "Pumpkin", "Cinderella")那么有没有办法从类型检查中排除单行,或者格式化这条长行,以便跳过类型检查,并且行长度符合 pep-8 标准?
2 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
有什么问题:
option_defaults = (1, 2, "White Horse", "Pumpkin", "Cinderella")
ConfigOption.__new__.__defaults__ = option_defaults # type: ignore
MMMHUHU
TA贡献1834条经验 获得超8个赞
Enum 似乎遵循您所需的约束,并且非常简洁。
您可以使用Functional API,它本身说semantics resemble namedtuple
>>> from enum import Enum
>>> Enum('ConfigOption', 'one two animal vehicle fairytale')
<enum 'ConfigOption'>
>>> ConfigOption = Enum('ConfigOption', 'one two animal vehicle fairytale')
>>> [c for c in ConfigOption]
[<ConfigOption.one: 1>, <ConfigOption.two: 2>, <ConfigOption.animal: 3>, <ConfigOption.vehicle: 4>, <ConfigOption.fairytale: 5>]
添加回答
举报
0/150
提交
取消