Ticker

6/recent/ticker-posts

Decorators in Python

Decorators in Python

Introduction

Decorators in Python are a powerful concept that allows you to modify or extend the behavior of functions or methods. They are functions themselves and are commonly used for adding functionalities to existing functions without modifying their code.

How Decorators Work

  1. Defining a Decorator: A decorator is a higher-order function that takes another function as an argument and returns a new function that usually enhances the input function.

  2. Syntax: The '@' symbol is used to apply a decorator to a function. It is placed before the function definition.

Example:

python
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function execution")
result = func(*args, **kwargs)
print("After function execution")
return result
return wrapper

@my_decorator
def greet(name):
print(f"Hello, {name}!")

greet("John")

Explanation:

  • We define a decorator called my_decorator that takes a function func as input.
  • Inside the my_decorator, we define a nested function wrapper which adds extra functionality before and after calling the original function func.
  • The original function func is invoked within the wrapper function using func(*args, **kwargs).
  • When we decorate the greet function with @my_decorator, it becomes equivalent to greet = my_decorator(greet).
  • Thus, whenever we call greet("John"), the my_decorator will be applied, and "Before function execution" and "After function execution" messages will be printed around the greeting message.

Conclusion

Decorators provide a clean and efficient way to modify or extend the behavior of functions in Python. They are widely used for logging, authentication, caching, and other cross-cutting concerns in various applications. Understanding decorators can significantly enhance your Python programming skills.

Post a Comment

0 Comments