如何在python3中注释生成器? [英] How to annotate a generator in python3?
本文介绍了如何在python3中注释生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python 3.x 支持(可选)函数注解:
Python 3.x supports (optional) function annotations:
def add_ints(x:int, y:int) -> int :
return x+y
我有时会遇到关于如何表示可以表示给定类型"的问题,这一次,我有一个返回生成器的函数:
I sometimes encounter problems as to how to represent a given "type" can be represented, and this time, I have a function that returns a generator:
def myfunc(x: [int]) -> "generator that returns ints":
# ^~~~~~~~~~~~~~~~~~~~~~~~~~
return (n for n in x if n%2 == 0)
我应该如何注释返回值?有什么参考资料可以参考吗?
How should I annotate the return value? Is there any reference I can consult to?
推荐答案
typing module 定义了 Generator 类型,你可以像这样使用:
The typing module defines the Generator type, which you can use like:
Generator[yield_type, send_type, return_type]
另见PEP 0484.
这篇关于如何在python3中注释生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文