类型提示、链式赋值和多重赋值

28

我猜这两个问题是相关的,所以我会一起发表:

1. - 是否可以在链式赋值中使用类型提示?

这两个尝试失败了:

>>> def foo(a:int):
...     b: int = c:int = a
  File "<stdin>", line 2
    b: int = c:int = a
              ^
SyntaxError: invalid syntax
>>> def foo(a:int):
...     b = c:int = a
  File "<stdin>", line 2
    b = c:int = a
         ^
SyntaxError: invalid syntax

2. - 是否可以在多个赋值中使用类型提示?

这是我的几次尝试:

>>> from typing import Tuple
>>> def bar(a: Tuple[int]):
...     b: int, c:int = a
  File "<stdin>", line 2
    b: int, c:int = a
          ^
SyntaxError: invalid syntax
>>> def bar(a: Tuple[int]):
...     b, c:Tuple[int] = a
... 
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated
>>> def bar(a: Tuple[int]):
...     b, c:int = a
... 
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated

我知道在这两种情况下类型都是从a的类型提示中推断出来的,但是我有一个很长的变量列表(在类的__init__中),我想要更加明确。

我正在使用Python 3.6.8。

1个回答

39
  1. As explicitly stated in PEP 526, section "Rejected/postponed proposals", annotations in chained assignments are not supported. Quoting the PEP:

    This has problems of ambiguity and readability similar to tuple unpacking, for example in:
    x: int = y = 1
    z = w: int = 1
    it is ambiguous, what should the types of y and z be? Also the second line is difficult to parse.

  2. For unpacking, per the same PEP, you should place bare annotations for your variables before the assignment. Example from the PEP:

    # Tuple unpacking with variable annotation syntax
    header: str
    kind: int
    body: Optional[List[str]]
    header, kind, body = message
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接