繁体   English   中英

python functools.singledispatch 是否适用于 Generator 类型?

[英]Does python functools.singledispatch work with Generator type?

我通过添加生成器类型的注册扩展了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不适用于生成器?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM