我想这两个问题是相关的,所以我将它们放在一起:
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。
-
正如明确指出的PEP 526 https://www.python.org/dev/peps/pep-0526/,“拒绝/推迟的提案”部分,不支持链接作业中的注释。引用 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)