当也遇到同样的问题时,我很不高兴看到Martijn Pieters 的回答。因为我想要一种“快速”和“简单”的方法来解决这个问题。
所以我首先尝试了这里列出的其他建议。
注意:我使用 VSCode 和 Pylance 作为语言服务器
Zaffys 的回答是我最喜欢的
def demystify(mystery: Annotated[Tuple[int], 6]):
a, b, c, d, e, f = mystery
print(a, b, c, d, e, f)
函数的提示看起来像这样:我也得到了该行demystify: (mystery: Tuple[int]) -> None
的 Pylance 错误Tuple size mismatch: expected 6 but received
a, b, c, d, e, f = mystery
接下来我尝试Tuple[6 * (int, )]
了 balu 在Martijn Pieters 的评论中提到的答案
def demystify(mystery: Tuple[6 * (int,)]):
a, b, c, e, f, g = mystery
print(a, b, c, e, f, g)
导致与以前相同的 Pylance 错误。该功能的提示是这样的:demystify: (mystery: Tuple[Tuple[Type[int], ...]]) -> None
回到写下预期长度:
def demystify(mystery: Tuple[int, int, int, int, int, int]):
a, b, c, e, f, g = mystery
print(a, b, c, e, f, g)
这解决了 Pylance 错误,并给了我一个“清晰”的功能提示:demystify: (mystery: Tuple[int, int, int, int, int, int]) -> None
但就像 John Brodie 一样,我对这个解决方案并不满意。
现在回到最初不需要的答案:
class MysteryType(NamedTuple):
a: int
b: int
c: int
d: int
e: int
f: int
g: int
def demystify(mystery: MysteryType):
print(*mystery)
函数提示现在看起来更加神秘:demystify: (mystery: MysteryType) -> None
但是创建一个新的 MysteryType 可以为我提供所需的所有信息:(a: int, b: int, c: int, d: int, e: int, f: int, g: int)
我也可以在其他方法和函数中使用 MysteryType 而无需计算类型提示。
因此,长话短说并解释 Python 之禅:
NamedTuples 是一个很棒的想法——让我们做更多的事情!