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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With