【问题标题】:Type hints and chained assignment and multiple assignments类型提示和链式赋值以及多重赋值
【发布时间】:2019-10-29 21:45:21
【问题描述】:

我猜这两个问题是相关的,所以我将它们一起发布:

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。

【问题讨论】:

    标签: python python-3.x type-hinting chained-assignment


    【解决方案1】:
    1. 正如PEP 526“被拒绝/推迟的提案”部分中明确指出的那样,不支持链式分配中的注释。引用 PEP:

      这有类似于元组解包的歧义和可读性问题,例如在:
      x: int = y = 1
      z = w: int = 1
      它是模棱两可的,y和z的类型应该是什么?第二行也很难解析。

    2. 对于解包,根据相同的 PEP,您应该在赋值之前为变量放置裸注。 PEP 的示例:

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

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 1970-01-01
      • 2021-11-27
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      相关资源
      最近更新 更多