gpt4 book ai didi

python - 返回多个函数的装饰器

转载 作者:太空狗 更新时间:2023-10-30 02:51:12 24 4
gpt4 key购买 nike

我想编写一个装饰器,将多个函数放入模块命名空间中。考虑以下模块:

# my_module.py


from scipy import signal


@desired_decorator(new_size=(8, 16, 32))
def resample(x, new_size):
return signal.resample(x, new_size)

我希望现在能够从 my_module 导入 resample_8resample_16resample_32。我可以编写装饰器并让它返回一个函数列表,但如何才能使这些函数在模块命名空间中可用?

最佳答案

由于您可以在不使用偷偷摸摸的黑客的情况下分配给全局字典,这几乎是可能的。 (语法不错)

编辑:K,也许它有点偷偷摸摸。没有监督的 Pythonista,不要在家里尝试这个。 martineau

EDIT2:可以通过使用堆栈自省(introspection)来获取调用者的全局变量,这可以避免导入问题,但是在非全局命名空间中调用时它不会起作用,或者在 6 个月内消除您的困惑。 user2357112

globals() 返回全局变量的字典。分配给它使用户可以导入这些功能

functools.partial 是创建偏函数的好方法。这基本上是一个“半完整”的函数调用。创建一个部分函数使其记住参数和关键字参数,调用该部分函数将使用参数和关键字参数调用原始函数。了解更多信息 here .

这是你想要的装饰器,但我强烈建议不要使用它。

from functools import partial

def desired_decorator(**kwargs):
# make sure there's only one keyword argument
assert len(kwargs) == 1
# unpack the single keyword and the values
keyword, values = (*kwargs.items(),)[0]
# this is the actual decorator that gets called
def _make_variants(func):
for value in values:
# assign to the globals dictionary
globals()[
f"{func.__name__}_{value}"
] = partial(func, **{keyword: value})
# keep the original function available
return func
return _make_variants

我的替代方案是使用 Chris据说从装饰器创建许多功能不利于维护和清晰度。

这是我建议的代码,但您可以根据需要使用上面的代码。

from functools import partial

# assign your function things here
resample_8 = partial(resample, new_size=8)
# repeat for other names

关于python - 返回多个函数的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720143/

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