Understanding Decorators
Let's start with a simple example. Open up a new Python interpreter session:
python3
We have a function that calculates the square of a number:
def square(x):
return x**2
Now let's say we want to add a feature to the square
function that logs the input and output of the function every time it is called. We can do this using a decorator.
Here's the code for the logger
decorator:
def logger(func):
def wrapper(x):
print("Calling function:", func.__name__)
print("Input:", x)
result = func(x)
print("Output:", result)
return result
return wrapper
Now we can use this decorator to enhance the square
function:
@logger
def square(x):
return x**2
When we call square(5)
, the output will be:
Calling function: square
Input: 5
Output: 25
As you can see, the decorator has added the desired functionality to the square
function without changing its source code.