【问题标题】:Why are parentheses required for assignment of a tuple to an annotated variable?为什么将元组分配给带注释的变量需要括号?
【发布时间】:2018-06-05 13:12:54
【问题描述】:

当我有一条看起来像这样的线时:

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

…我收到了SyntaxError,但是当我这样做时:

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

…它是有效的。

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

【问题讨论】:

  • 我不知道原因,但在文档和原始 PEP 中明确指出了这一点。
  • Docs: "与普通赋值语句的区别在于只允许单个目标和单个右侧值。"
  • PEP 526: "只允许单个赋值目标和单个右侧值。"

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


【解决方案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

多种类型/变量

一个明显的问题是是否允许组合类型声明 使用元组解包(例如a, b, c = x)。这导致(真实或 感知)模棱两可,我建议支持这一点。如果有一个 类型注释左边只能有一个变量,一个 价值在它的右边。 这仍然允许元组打包(只需将 圆括号中的元组),但它不允许元组解包。 (它已经 建议允许多个带括号的变量名称或类型 括号内,但这些对我来说都没有吸引力。)

【讨论】:

    猜你喜欢
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2018-12-27
    • 2012-06-15
    • 2013-04-07
    • 2014-08-09
    • 1970-01-01
    相关资源
    最近更新 更多