简体   繁体   中英

Making a single decorator of out multiple

Say, I have something like:

@decorator1
@decorator2
def myfunc()
   # ....

How do I declare a new decorator both_decorators which would invoke decorator1 and decorator2 in order, essentially making it an alias for them? So that I could write instead:

@both_decorators
def myfunc()
   # ....

The idea is to save typing when multiple decorators are used the same way in many cases.

Simple:

def both_decorators(func):
    return decorator1(decorator2(func))

because that's all decorators do, really.

Yes, you can. Something along the lines of:

def both_decorators(*decs):
    def decorator(dc):
        for dec in reversed(decs):
            dc = dec(dc)
        return dc
    return decorator

Then all you would need to do is add them

@both_decorators(decorator1, decorator2)
def myfunc():
    #something happening here.

Personally I would prefer this, as you can choose which decorator you would want and which not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM