Decorating functions
Decorators are functions or classes that wrap other functions and/or classes. In its most basic form, you can view a regular function call as add(1, 2)
, which transforms into decorator(add(1, 2))
when applying a decorator. There’s slightly more to it, but we will come to that later. Let’s implement that decorator()
function:
>>> def decorator(function):
... return function
>>> def add(a, b):
... return a + b
>>> add = decorator(add)
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 decorate a function using the @
operator as a shortcut:
>>> @decorator
... def add(a, b):
... return a + b
This example shows the simplest and most useless decorator you can get: simply returning the input function and doing nothing else.
From this, you might wonder what the use of a decorator...