我具有仅对相关数据进行分组的这种数据类型。它应该是类似结构的东西,所以我选择了namedtuple
。
ConfigOption = namedtuple('ConfigOption', 'one two animal vehicle fairytale')
另一方面,namedtuple
没有默认值,因此我居住在another answer中提出的黑客手段。
ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella")
显然,这会使类型检查失败:error: "Callable[[Type[NT], Any, Any, Any, Any, Any], NT]" has no attribute "__defaults__"
由于我很清楚这是一种黑客行为,因此我告诉类型检查器,因此使用内联注释# type: disable
:
ConfigOption.__new__.__defaults__ = (1, 2, "White Horse", "Pumpkin", "Cinderella") # type: disable
这时...该行变得太长。我不知道如何打破这一行,以使其在语法上正确,同时使类型检查器跳过它:
# the ignore is on the wrong line
ConfigOption.__new__.__defaults__ = \
(1, 2, "White Horse", "Pumpkin", "Cinderella") # type: ignore
# unexpected indentation
ConfigOption.__new__.__defaults__ = # type: ignore
(1, 2, "White Horse", "Pumpkin", "Cinderella")
有没有办法从类型检查中排除单行,或格式化该长行,从而跳过类型检查,并且行长符合pep-8?
答案 0 :(得分:2)
怎么了?
option_defaults = (1, 2, "White Horse", "Pumpkin", "Cinderella")
ConfigOption.__new__.__defaults__ = option_defaults # type: ignore
答案 1 :(得分:0)
枚举似乎遵循您所要求的约束,并且非常简洁。
您可以使用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>]