具有yield的Python函数的正确类型注释

时间:2016-07-17 09:13:47

标签: python generator coroutine static-typing mypy

在阅读Eli Bendersky的文章on implementing state machines via Python coroutines后,我想...

  • 查看他在Python3下运行的示例
  • 并为发生器添加适当的类型注释

我成功完成了第一部分(但没有使用async def s或yield from,我基本上只是移植了代码 - 所以任何改进都是最受欢迎的) 。

但是我需要一些关于协同程序类型注释的帮助:

#!/usr/bin/env python3

from typing import Callable, Generator

def unwrap_protocol(header: int=0x61,
                    footer: int=0x62,
                    dle: int=0xAB,
                    after_dle_func: Callable[[int], int]=lambda x: x,
                    target: Generator=None) -> Generator:
    """ Simplified protocol unwrapping co-routine."""
    #
    # Outer loop looking for a frame header
    #
    while True:
        byte = (yield)
        frame = []  # type: List[int]

        if byte == header:
            #
            # Capture the full frame
            #
            while True:
                byte = (yield)
                if byte == footer:
                    target.send(frame)
                    break
                elif byte == dle:
                    byte = (yield)
                    frame.append(after_dle_func(byte))
                else:
                    frame.append(byte)


def frame_receiver() -> Generator:
    """ A simple co-routine "sink" for receiving full frames."""
    while True:
        frame = (yield)
        print('Got frame:', ''.join('%02x' % x for x in frame))

bytestream = bytes(
    bytearray((0x70, 0x24,
               0x61, 0x99, 0xAF, 0xD1, 0x62,
               0x56, 0x62,
               0x61, 0xAB, 0xAB, 0x14, 0x62,
               0x7)))

frame_consumer = frame_receiver()
next(frame_consumer)  # Get to the yield

unwrapper = unwrap_protocol(target=frame_consumer)
next(unwrapper)  # Get to the yield

for byte in bytestream:
    unwrapper.send(byte)

运行正常......

$ ./decoder.py 
Got frame: 99afd1
Got frame: ab14

......还有typechecks:

$ mypy --disallow-untyped-defs decoder.py 
$

但我很确定我能做得比在类型规范中使用Generator基类更好(就像我对Callable所做的那样)。我知道它需要3个类型参数(Generator[A,B,C]),但我不确定它们在这里是如何指定的。

欢迎任何帮助。

3 个答案:

答案 0 :(得分:23)

我自己想出了答案。

我进行了搜索,但没有找到official typing documentation for Python 3.5.2Generator的3种类型参数的文档 - 除了真正神秘的提及......

class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])

幸运的是,the original PEP484(开始这一切)更有帮助:

"生成器函数的返回类型可以通过typing.py模块提供的泛型类型Generator [yield_type,send_type,return_type]进行注释:

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

基于此,我能够为我的Generators注释,并看到mypy确认我的作业:

from typing import Callable, Generator

# A protocol decoder:
#
# - yields Nothing
# - expects ints to be `send` in his yield waits
# - and doesn't return anything.
ProtocolDecodingCoroutine = Generator[None, int, None]

# A frame consumer (passed as an argument to a protocol decoder):
#
# - yields Nothing
# - expects List[int] to be `send` in his waiting yields
# - and doesn't return anything.
FrameConsumerCoroutine = Generator[None, List[int], None]


def unwrap_protocol(header: int=0x61,
                    footer: int=0x62,
                    dle :int=0xAB,
                    after_dle_func: Callable[[int], int]=lambda x: x,
                    target: FrameConsumerCoroutine=None) -> ProtocolDecodingCoroutine:
    ...

def frame_receiver() -> FrameConsumerCoroutine:
    ...

我通过例如测试我的作业交换类型的顺序 - 然后按预期,mypy抱怨并要求正确的(如上所示)。

完整代码is accessible from here

我会将问题保持开放几天,以防有人想要加入 - 特别是在使用Python 3.5的新协程样式(async def等)方面 - 我会很感激关于他们如何在这里使用。

答案 1 :(得分:5)

如果您使用yield有一个简单的函数,则可以使用Iterator类型而不是Generator来注释其结果:

from typing import Iterator

def count_up() -> Iterator[int]:
    for x in range(10):
        yield x

答案 2 :(得分:2)

在撰写本文时,Python documentation 还明确提到了如何处理异步情况(已接受的答案中已经提到了非异步示例)。

从那里引用:

async def echo_round() -> AsyncGenerator[int, float]:
    sent = yield 0
    while sent >= 0.0:
        rounded = await round(sent)
        sent = yield rounded

(第一个参数是yield-type,第二个参数是send-type)或简单情况(其中send-type 为None)

async def infinite_stream(start: int) -> AsyncIterator[int]:
    while True:
        yield start
        start = await increment(start)