Python Decorator
Table of Content:
Python Decorator
In Python, a decorator is a function that takes another function as input, adds some functionality to it, and returns the modified function. Decorators provide a way to modify the behavior of a function without changing its source code.
Decorators are typically defined using the @
symbol followed by the name of the decorator function, and they are placed above the function definition. When a decorated function is called, it is actually the modified version of the function that is executed, with the added functionality from the decorator.
Here's an example of a simple decorator that adds some logging functionality to a function:
def log(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__}") result = func(*args, **kwargs) print(f"Function {func.__name__} returned {result}") return result return wrapper @log def add(a, b): return a + b
In this example, the log
function is defined as a decorator that takes a function func
as input and returns a new function wrapper
. The wrapper
function adds logging functionality to the input function func
, which is called with the same arguments and returns the result.
The @log
decorator is then applied to the add
function, which adds logging functionality to the function. When the add
function is called, it is actually the modified wrapper
function that is executed, which logs the function call and return value:
>>> add(2, 3) Calling function add Function add returned 5 5
This is a simple example, but decorators can be used for a variety of purposes, such as adding caching, memoization, or error handling functionality to functions.