我的函数应该返回一个生成器,该生成器通过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]
在我的情况下,YieldType
,SendType
和ReturnType
是什么?
答案 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
表现为反协,而非协变或 不变地。如果生成器仅产生值,请设置
SendType
和ReturnType
到无: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