python - Singledispatch 装饰器并不像宣传的那样工作

标签 python single-dispatch

我正在测试 python 的 singledispatch:https://docs.python.org/3/library/functools.html?highlight=singledispatch#functools.singledispatch

根据文档, block A 应该和 block B 一样工作。但是,您可以在输出中看到只有 block B 按预期工作。

这里有什么问题吗?谢谢。

from functools import singledispatch


# Block A
@singledispatch
def divider(a, b=1):
    print(a, b)

@divider.register
def _(a: int, b=1):
    print(a/b)

@divider.register
def _(a: str, b=1):
    print(a[:len(a)//b])

divider(25, 2)
divider('single dispatch practice', 2)


# Block B
@singledispatch
def div(a, b=1):
    print(a, b)


@div.register(int)
def _(a: int, b=1):
    print(a/b)


@div.register(str)
def _(a: str, b=1):
    print(a[:len(a)//b])

div(25 , 2)
div('single dispatch practice', 2)

输出:

>> 25 2
>> single dispatch practice 2
>> 12.5
>> single dispatch

最佳答案

I am testing python's singledispatch (...) What's is the problem here?

您使用类型注释是正确的,但是@singledispatch仅使用它们since Python 3.7 (注释在 Python 3.0 中引入,singledispatch 在 3.4 中引入)。因此

# works since 3.4
@foo.register(str)
def foo_str(a: str):
    ...

# works since 3.7
@foo.register
def foo_str(a: str)
    ...

关于python - Singledispatch 装饰器并不像宣传的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114481/

相关文章:

python - 为什么从 CSV 文件导入数据时出现此 DBeaver 错误?

python - 如何将 float 显示为货币前带负号的货币

python - 我可以向用户询问一个号码,然后将对应号码的图像粘贴到空白图像中吗?

python - Flask restx 模型嵌套通配符字典

python - 列出 Python 中的简单切片?

python - 如何结合@singledispatch和@lru_cache?

python - lru_cache 干扰 single_dispatch 完成的类型检查