ste*_*fen 6 python type-hinting python-3.x chained-assignment
我猜这两个问题是相关的,因此我将它们一起发布:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我知道,在两种情况下,类型都是从a的类型提示中推断出来的,但是我有一个很长的变量列表(在__init__一个类的中),并且我想更加明确。
我正在使用Python 3.6.8。
如PEP 526中 “拒绝/推迟的提案”部分明确指出的,不支持链式分配中的注释。引用PEP:
这具有与元组拆包类似的歧义性和可读性问题,例如:
x: int = y = 1
z = w: int = 1
不明确,y和z的类型应该是什么?第二行也很难解析。
要解压缩,请按照相同的PEP,在分配之前为变量添加裸注。PEP的示例:
# Tuple unpacking with variable annotation syntax
header: str
kind: int
body: Optional[List[str]]
header, kind, body = message
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |