为什么需要括号来将元组赋值给带注释的变量?

时间:2017-12-23 01:25:23

标签: python python-3.x annotations syntax-error iterable-unpacking

当我有一行如下:

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

...我得到SyntaxError,但是当我这样做时:

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

......它有效。

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

1 个答案:

答案 0 :(得分:0)

这是故意的。在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

  

多个类型/变量

     

一个显而易见的问题是是否允许组合类型声明   使用元组解包(例如a, b, c = x)。这导致(真实或   感觉到歧义,我建议来支持这一点。如果有的话   类型注释左边只能有一个变量,一个变量   价值在右边。 这仍然允许元组打包(只需放入   括号中的元组)但它不允许元组解包。 (它已经   建议允许多个带括号的变量名或类型   在括号内,但这些都不会对我有吸引力。)