-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Mastering Python
By :
Essentially, a decorator is nothing more than a function or class wrapper. If we have a function called spam and a decorator called eggs, then the following would decorate spam with eggs:
spam = eggs(spam)
To make the syntax easier to use, Python has a special syntax for this case. So, instead of adding a line such as the preceding one below the function, you can simply decorate a function using the @ operator:
@eggs
def spam():
passThe decorator simply receives the function and returns a—usually different—function. The simplest possible decorator is:
def eggs(function):
return functionLooking at the earlier example, we realize that this gets spam as the argument for function and returns that function again, effectively changing nothing. Most decorators nest functions, however. The following decorator will print all arguments sent to spam and pass them to spam unmodified:
>>> import functools >>> def eggs(function): ... @functools...