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

问题描述 投票:3回答:1

当我有一个看起来像这样的行:

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

...我得到了一个SyntaxError,但当我这样做时:

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

......这是有效的。

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

python python-3.x annotations syntax-error iterable-unpacking
1个回答
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中:

Multiple types/variables

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

© www.soinside.com 2019 - 2024. All rights reserved.