问题描述
假设我有一个由多个装饰器装饰的函数.
Let's say I have a function that is decorated by multiple decorators.
# file.py
@deco1
@deco2('param')
@deco3(
'multiple',
'long',
'params'
)
@deco4('multiple', 'params')
def foo():
"""Function foo
"""
pass
让我们说它看起来很脏.很脏.
Let's just say it looks very dirty. VERY dirty.
我希望能够做这样的事情.
I want to be able to do something like this.
# another_file.py
@deco1
@deco2('param')
@deco3(
'multiple',
'long',
'params'
)
@deco4('multiple', 'params')
def all_decorators_for_foo():
...
# file.py
from another_file import all_decorators_for_foo
@all_decorators_for_foo
def foo():
"""Yay!
"""
...
仅出于上下文考虑,多个装饰器是sanic框架的草率文档装饰器.
Just for the sake of context, the multiple decorators are swagger documentation decorators for sanic framework.
在python中是否有可能实现类似的目的?
Is it possible in python to achieve something similar to this?
此问题不能以任何方式回答我的问题问题.装饰器无论如何都可以堆叠在一起并使用.我想要一种可以代替所有堆叠式装饰器的装饰器.
This question does not in any way answer my question. Decorators can anyway be stacked together and used. I want some sort of decorator that can be used in place of all the stacked decorators.
推荐答案
可以.您可以使另一个装饰器返回装饰后的函数,如下所示: all_decorators_for_foo.py
Yes you could. You can make another decorator that returns the decorated function like so:all_decorators_for_foo.py
def all_decorators_for_foo(func):
return deco1()(
deco2('param')(
deco3(
'multiple',
'long',
'params'
)(
deco4('multiple', 'params')(
func
)
)
)
)
,然后在 file.py
from another_file import all_decorators_for_foo
@all_decorators_for_foo
def foo():
pass
这篇关于如何创建一个可以将多个装饰器应用于另一个函数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!