gpt4 book ai didi

python - 为什么将元组分配给带注释的变量需要括号?

转载 作者:行者123 更新时间:2023-11-28 19:05:06 25 4
gpt4 key购买 nike

当我有这样一行时:

t: Tuple[int, int] = 0, 1

…我得到了一个SyntaxError,但是当我这样做的时候:

t = 0, 1
t: Tuple[int, int] = (0, 1)

……这是有效的。

这是故意的吗?具有类型说明符且没有括号的解析树中是否存在歧义?

最佳答案

这是故意的。在 python-ideas 邮件列表上关于变量注释的原始提案中,Guido van Rossum writes :

Third, there's an annoying thing with tuples/commas here. On the one
hand, in a function declaration, we may see (a: int = 0, b: str = '').
On the other hand, in an assignment, we may see

a, b = 0, ''

Suppose we wanted to add types to the latter. Would we write this as

a, b: int, str = 0, ''

or as

a: int, b: str = 0, ''

??? Personally I think neither is acceptable, and we should just write it as

a: int = 0
b: str = ''

but this is a slight step back from

a, b = 0, '' # type: (int, str)

... 然后,在相关的 GitHub 中 issue :

Multiple types/variables

An obvious question is whether to allow combining type declarations with tuple unpacking (e.g. a, b, c = x). This leads to (real or perceived) ambiguity, and I propose not to support this. If there's a type annotation there can only be one variable to its left, and one value to its right. This still allows tuple packing (just put the tuple in parentheses) but it disallows tuple unpacking. (It's been proposed to allow multiple parenthesized variable names, or types inside parentheses, but none of these look attractive to me.)

关于python - 为什么将元组分配给带注释的变量需要括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com