Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pack several decorators into one?

I have several decorators on each function, is there a way to pack them in to one instead?

@fun1
@fun2
@fun3
def do_stuf():
    pass

change to:

@all_funs #runs fun1 fun2 and fun3, how should all_funs look like?
def do_stuf():
    pass
like image 416
pprzemek Avatar asked Feb 02 '10 09:02

pprzemek


People also ask

Can a function have 2 decorators?

Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python.

How many decorators can be applied to a function in Python?

Well, there are 1000 possibilities. Classic uses are extending a function behavior from an external lib (you can't modify it), or for debugging (you don't want to modify it because it's temporary). Of course the good thing with decorators is that you can use them right away on almost anything without rewriting.

How do decorators work in Python?

Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

Is decorators important in Python?

Needless to say, Python's decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own.


1 Answers

A decorator is in principle only syntactic sugar for this:

def do_stuf():
    pass

do_stuf = fun1(do_stuf)

So in your all_fun, all you should need to do is to wrap the function in the same kind of chain of decorators:

def all_funs(funky):
    return fun1(fun2(fun3(fun4(funky)))

Things get a little bit (but only a litte) more complex if you have parameters to the decorators.

like image 169
Lennart Regebro Avatar answered Sep 21 '22 14:09

Lennart Regebro