我的函数应该返回一个生成器,该生成器从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
是什么?
来自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.PosixPath
的实例,所以可以这样做>
import pathlib
from typing import Generator
def get_waves_generator(directory: str) -> Generator[pathlib.PosixPath, None, None]:
gen = pathlib.Path(directory).rglob('*.wav')
return gen