gpt4 book ai didi

python - Python 重载装饰器

转载 作者:太空狗 更新时间:2023-10-29 21:50:45 28 4
gpt4 key购买 nike

我知道编写关心参数类型的函数不是 Pythonic,但有些情况下根本不可能忽略类型,因为它们的处理方式不同。

在你的函数中有一堆 isinstance 检查是丑陋的;是否有可用的函数装饰器来启用函数重载?像这样:

@overload(str)
def func(val):
print('This is a string')

@overload(int)
def func(val):
print('This is an int')

更新:

这是我在 David Zaslavsky's answer 上留下的一些评论:

With a few modification[s], this will suit my purposes pretty well. One other limitation I noticed in your implementation, since you use func.__name__ as the dictionary key, you are prone to name collisions between modules, which is not always desirable. [cont'd]

[cont.] For example, if I have one module that overloads func, and another completely unrelated module that also overloads func, these overloads will collide because the function dispatch dict is global. That dict should be made local to the module, somehow. And not only that, it should also support some kind of 'inheritance'. [cont'd]

[cont.] By 'inheritance' I mean this: say I have a module first with some overloads. Then two more modules that are unrelated but each import first; both of these modules add new overloads to the already existing ones that they just imported. These two modules should be able to use the overloads in first, but the new ones that they just added should not collide with each other between modules. (This is actually pretty hard to do right, now that I think about it.)

其中一些问题可以通过稍微更 retrofit 饰器语法来解决:

第一个.py

@overload(str, str)
def concatenate(a, b):
return a + b

@concatenate.overload(int, int)
def concatenate(a, b):
return str(a) + str(b)

second.py

from first import concatenate

@concatenate.overload(float, str)
def concatenate(a, b):
return str(a) + b

最佳答案

从 Python 3.4 开始,functools 模块支持 @singledispatch装饰器。它是这样工作的:

from functools import singledispatch


@singledispatch
def func(val):
raise NotImplementedError


@func.register
def _(val: str):
print('This is a string')


@func.register
def _(val: int):
print('This is an int')

用法

func("test") --> "This is a string"
func(1) --> "This is an int"
func(None) --> NotImplementedError

关于python - Python 重载装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8654666/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com