returns 多种功能的装饰器
A decorator that returns multiple functions
我想编写一个装饰器,将多个函数放入模块名称空间中。考虑以下模块:
# 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_8
、resample_16
和 resample_32
。我可以编写装饰器并让它 return 一个函数列表,但是这些函数如何在模块命名空间中可用?
由于您可以在不使用偷偷摸摸的黑客的情况下分配给全局字典,这几乎是可能的。 (语法不错)
编辑:K,也许是 lil 有点偷偷摸摸。没有监督的 Pythonista,不要在家里尝试这个。 martineau
EDIT2:可以通过使用堆栈自省来获取调用者的全局变量,这避免了导入问题,但是在 non-global 命名空间中调用时它不会起作用,或者在 6 个月内消除你的困惑. user2357112
globals()
returns 一个全局变量的字典。分配给它可以让用户导入这些功能
functools.partial
是创建部分函数的好方法。这基本上是一个 'half complete' 函数调用。创建一个部分函数使其记住参数和关键字参数,调用该部分函数将使用参数和关键字参数调用原始函数。阅读更多相关信息 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
我想编写一个装饰器,将多个函数放入模块名称空间中。考虑以下模块:
# 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_8
、resample_16
和 resample_32
。我可以编写装饰器并让它 return 一个函数列表,但是这些函数如何在模块命名空间中可用?
由于您可以在不使用偷偷摸摸的黑客的情况下分配给全局字典,这几乎是可能的。 (语法不错)
编辑:K,也许是 lil 有点偷偷摸摸。没有监督的 Pythonista,不要在家里尝试这个。 martineau
EDIT2:可以通过使用堆栈自省来获取调用者的全局变量,这避免了导入问题,但是在 non-global 命名空间中调用时它不会起作用,或者在 6 个月内消除你的困惑. user2357112
globals()
returns 一个全局变量的字典。分配给它可以让用户导入这些功能
functools.partial
是创建部分函数的好方法。这基本上是一个 'half complete' 函数调用。创建一个部分函数使其记住参数和关键字参数,调用该部分函数将使用参数和关键字参数调用原始函数。阅读更多相关信息 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