Glob生成器的类型注释

时间:2020-04-26 17:19:41

标签: python python-3.x path generator

我的函数应该返回一个生成器,该生成器通过Path模块中的pathlib产生具有特定签名的文件。问题是我不理解如何在Python 3中正确注释该函数。

功能如下:

from pathlib import Path
from typing import Generator

def get_waves_generator(directory: str) -> ???:
    gen = Path(directory).rglob('*.wav')
    return gen

我找到了this answer,它实际上是文档的副本。我需要用以下内容注释

Generator[YieldType, SendType, ReturnType]

在我的情况下,YieldTypeSendTypeReturnType是什么?

1 个答案:

答案 0 :(得分:1)

来自the docs

可以通过通用类型Generator[YieldType, SendType, ReturnType]注释生成器。例如:

def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'

请注意,与键入模块中的许多其他泛型不同, SendType中的Generator表现为反协,而非协变或 不变地。

如果生成器仅产生值,请设置SendTypeReturnType到无:

def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1

当该生成器返回pathlib.Path的实例时,您可以这样做

from pathlib import Path
from typing import Generator

def get_waves_generator(directory: str) -> Generator[Path, None, None]:
    gen = Path(directory).rglob('*.wav')
    return gen