类型提示和链式赋值和多重赋值
Type hints and chained assignment and multiple assignments
我想这两个问题是相关的,所以我将 post 放在一起:
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 的类型提示中推断出来的,但是我有一个很长的变量列表(在 class 的 __init__
中),我想要特别明确。
我正在使用 Python 3.6.8.
如 PEP 526 部分 "Rejected/postponed proposals" 中明确指出的那样,不支持链式赋值中的注释。引用 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.
对于解包,根据相同的 PEP,您应该在赋值之前为您的变量放置裸注释。来自 PEP 的示例:
# Tuple unpacking with variable annotation syntax
header: str
kind: int
body: Optional[List[str]]
header, kind, body = message
我想这两个问题是相关的,所以我将 post 放在一起:
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 的类型提示中推断出来的,但是我有一个很长的变量列表(在 class 的 __init__
中),我想要特别明确。
我正在使用 Python 3.6.8.
如 PEP 526 部分 "Rejected/postponed proposals" 中明确指出的那样,不支持链式赋值中的注释。引用 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.对于解包,根据相同的 PEP,您应该在赋值之前为您的变量放置裸注释。来自 PEP 的示例:
# Tuple unpacking with variable annotation syntax header: str kind: int body: Optional[List[str]] header, kind, body = message