python functools.singledispatch 是否适用于生成器类型?
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
.
<b>from types import GeneratorType</b>
@fun.register
def _(arg: Generator<b>Type</b>, 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
我通过添加生成器类型
的注册扩展了 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
.
<b>from types import GeneratorType</b>
@fun.register
def _(arg: Generator<b>Type</b>, 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