Python Decorator
A decorator is a particular type of function that is used to modify or enhance the behavior of other functions or methods without changing their source code. Decorators are often used to add functionality to functions or methods in a clean and reusable way.
Sample Code
# Define a simple decorator
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
# Use the decorator
@my_decorator
def say_hello():
print("Hello!")
# Call the decorated function
say_hello()
Output
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
In this example:
my_decorator
is a decorator function that takes another function (func
) as an argument.- Inside
my_decorator
, a nested function calledwrapper
is defined. Thiswrapper
function adds functionality before and after callingfunc
. - The
@my_decorator
syntax is used to decorate thesay_hello
function. This means that whensay_hello
is called, it will invoke thewrapper
function, which in turn calls the originalsay_hello
function along with additional behavior.
When you run this code, you’ll see that the decorated say_hello
function prints messages before and after the "Hello!" message.
Decorators are commonly used for various purposes in Python, such as:
- Logging: To log information about function calls.
- Authorization: To check if a user has the required permissions before executing a function.
- Timing: To measure the execution time of functions.
- Caching: To cache the results of expensive function calls.
- Validation: To validate function arguments before execution.
Python’s built-in decorators include @staticmethod
, @classmethod
, and @property
, among others. Also, you can create custom decorators to suit your specific needs, as demonstrated in the above example.
Decorators are a powerful and flexible feature in Python, enabling you to keep your code clean, modular, and easy to maintain by separating concerns and adding functionality in a modular fashion.