类型提示和链接分配和多个分配

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

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

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个回答
6
投票
  1. PEP 526中“拒绝/推迟的提案”部分明确指出的,不支持链式分配中的注释。引用PEP:

    这具有与元组拆包类似的歧义和可读性问题,例如:x: int = y = 1z = 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
    
© www.soinside.com 2019 - 2024. All rights reserved.