如何在python3中注释生成器?

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)

  • 您可以更加抽象,并将返回类型声明为“Iterable”,因为所有迭代器都应该有一个“__iter__”方法(返回自身)。 (2认同)
  • @Blckknght。我认为“Iterator”更好,因为它更具体。使用“Iterable”,调用“next(fn(1))”将导致类型检查失败:“Iterable”没有“__next__”方法 (2认同)

pfp*_*ers 24

类型模块定义的发电机类型,您可以使用这样的:

Generator[yield_type, send_type, return_type] 
Run Code Online (Sandbox Code Playgroud)

另见PEP 0484.

  • @z33k _“如果您的生成器仅产生值,请将 SendType 和 ReturnType 设置为 None”_ - 来自 [`Generator` 文档](https://docs.python.org/3/library/typing.html#typing.发电机) (6认同)
  • 使用迭代器要简单得多,请参阅 Conchylicultor 的答案 (2认同)