提问人:McKay 提问时间:12/23/2017 最后编辑:Zero PiraeusMcKay 更新时间:12/26/2017 访问量:3888
为什么将元组分配给带注释的变量需要括号?
Why are parentheses required for assignment of a tuple to an annotated variable?
问:
当我有一行看起来像这样时:
t: Tuple[int, int] = 0, 1
...我得到一个 ,但是当我这样做时:SyntaxError
t = 0, 1
t: Tuple[int, int] = (0, 1)
...这是有效的。
这是故意的吗?解析树中是否存在带有类型说明符且没有 parens 的歧义?
答:
0赞
Zero Piraeus
12/26/2017
#1
这是故意的。在 python-ideas 邮件列表上关于变量注解的原始提案中,Guido van Rossum 写道:
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 问题中:
多种类型/变量
一个显而易见的问题是是否允许组合类型声明 使用元组解包(例如)。这导致(实数或 感知)模棱两可,我建议不支持这一点。如果有一个 类型注解 它的左边只能有一个变量,并且一个 值。这仍然允许元组打包(只需将 括号中的元组),但它不允许元组解包。(已经 建议允许多个带括号的变量名称或类型 在括号内,但这些对我来说都没有吸引力。
a, b, c = x
评论