glob生成器的类型注释

问题描述 投票:2回答:1

我的函数应该返回一个生成器,该生成器从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是什么?

python python-3.x path generator
1个回答
0
投票

来自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'

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.