Yos*_*osh 15 python annotations python-3.x
Python 3.x支持(可选)函数注释:
def add_ints(x:int, y:int) -> int :
return x+y
Run Code Online (Sandbox Code Playgroud)
我有时会遇到如何表示给定"类型"可以表示的问题,而这次,我有一个返回生成器的函数:
def myfunc(x: [int]) -> "generator that returns ints":
# ^~~~~~~~~~~~~~~~~~~~~~~~~~
return (n for n in x if n%2 == 0)
Run Code Online (Sandbox Code Playgroud)
我该如何注释返回值?有什么参考我可以咨询吗?
Con*_*tor 30
虽然Generator[x, y, z]存在,但大多数情况下,您可能希望使用不那么冗长的Iterator:
def fn(x: int) -> Iterator[int]:
return (n for n in range(x) if n%2 == 0)
Run Code Online (Sandbox Code Playgroud)
也适用于 yield
def fn(x: int) -> Iterator[int]:
for n in range(x):
yield n
Run Code Online (Sandbox Code Playgroud)
pfp*_*ers 24
该类型模块定义的发电机类型,您可以使用这样的:
Generator[yield_type, send_type, return_type]
Run Code Online (Sandbox Code Playgroud)
另见PEP 0484.
| 归档时间: |
|
| 查看次数: |
2743 次 |
| 最近记录: |