【问题标题】:Does python functools.singledispatch work with Generator type?python functools.singledispatch 是否适用于 Generator 类型?
【发布时间】:2020-11-16 21:35:40
【问题描述】:

我通过添加生成器类型的注册来扩展 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 不能与生成器一起使用吗?

【问题讨论】:

    标签: python functools single-dispatch


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-03-02
      • 1970-01-01
      相关资源
      最近更新 更多