In Python, a decorator is a powerful and flexible tool that allows you to modify or extend the behavior of functions or methods without changing their actual code. Decorators are often used to add functionality such as logging, access control, or instrumentation in a clean and reusable manner. By using decorators, you can enhance functions or methods dynamically, adhering to the DRY (Don't Repeat Yourself) principle.
A decorator is a function that takes another function (or method) as an argument and returns a new function that typically extends or alters the behavior of the original function. Decorators are commonly used to:
A decorator is applied to a function using the @
symbol followed by the decorator function's name, placed above the function definition.
@decorator_function
is the decorator being applied to function_to_decorate
.Here’s a step-by-step guide to creating and using a basic decorator:
my_decorator
is a decorator function that takes another function func
as an argument.wrapper
is an inner function that adds additional behavior before and after calling func
.Output:
The @my_decorator
syntax applies the my_decorator
to say_hello
, enhancing its behavior with additional print statements.
Decorators can also accept arguments, making them more flexible. To do this, you need an additional level of nested functions.
python
repeat
is a decorator factory that returns decorator_repeat
, which in turn returns wrapper
.Output:
The repeat
decorator causes the greet
function to be executed three times.
Logging Function Calls:
You can use decorators to automatically log function calls and their results.
Access Control and Authentication:
Decorators can enforce access control, such as requiring users to be authenticated before executing a function.
Caching Results:
Decorators can cache the results of expensive function calls to improve performance.
Decorators in Python provide a flexible way to modify or extend the behavior of functions or methods without altering their code. By understanding how to create and apply decorators, you can enhance functionality, enforce rules, and improve code maintainability. Whether you are logging, managing access control, or caching results, decorators are a powerful tool for writing cleaner and more modular Python code.