1

我通过添加生成器类型的注册扩展了https://docs.python.org/3/library/functools.html#functools.singledispatch的示例

from functools import singledispatch
from typing import Generator

@singledispatch
def fun(arg, verbose):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

@fun.register
def _(arg: list, verbose):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

# NEW CODE BELOW

@fun.register
def _(arg: Generator, verbose):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

fun([3,4,5], verbose=True)
fun((i for i in range(6, 10)), verbose=True)

虽然它适用于列表,但它似乎不适用于带有错误的生成器

    raise TypeError(
TypeError: Invalid annotation for 'arg'. typing.Generator is not a class.

预计singledispatch不适用于生成器吗?

4

1 回答 1

4

typing.Generator是类型提示,而不是类型。你需要types.GeneratorType.

from types import GeneratorType

@fun.register
def _(arg: GeneratorType, verbose):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

根据 ,对象不被视为类型提示的实例isinstance,它singledispatch用于决定将哪个函数用于给定参数。通过此更改,您将获得预期的输出

$ python3 tmp.py
Enumerate this:
0 3
1 4
2 5
Enumerate this:
0 6
1 7
2 8
3 9
于 2020-11-16T21:44:35.620 回答