Advanced Python: Decorators 🚀🐍

Decorators in Python allow you to modify or enhance functions without changing their actual code. They are widely used for logging, authentication, performance measurement, and more.
1️⃣ What is a Decorator?
A decorator is a function that takes another function as input and adds extra functionality to it without modifying its structure.
✅ Basic Decorator Example:
def decorator_function(original_function):
def wrapper():
print("Wrapper executed before", original_function.__name__)
original_function() # Call the original function
print("Wrapper executed after", original_function.__name__)
return wrapper
@decorator_function
def say_hello():
print("Hello, Python!")
say_hello()
🔹 Output:
Wrapper executed before say_hello
Hello, Python!
Wrapper executed after say_hello
✔ The wrapper() function wraps around the original function, adding behavior before and after execution.
2️⃣ Creating Custom Decorators
✅ Using *args and **kwargs to Handle Any Function:
def my_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
result = func(*args, **kwargs) # Execute original function
print(f"Function {func.__name__} executed successfully!")
return result
return wrapper
@my_decorator
def add(x, y):
return x + y
print(add(5, 3))
🔹 Output:
Calling function: add
Function add executed successfully!
8
✔ The decorator logs function calls without modifying add().
3️⃣ Using Multiple Decorators
You can stack multiple decorators on a function:
def uppercase_decorator(func):
def wrapper():
result = func().upper()
return result
return wrapper
def exclamation_decorator(func):
def wrapper():
return func() + "!!!"
return wrapper
@uppercase_decorator
@exclamation_decorator
def greet():
return "hello"
print(greet())
🔹 Output:
HELLO!!!
✔ Order matters: exclamation_decorator runs first, then uppercase_decorator.
4️⃣ Decorators with Arguments
Sometimes, decorators need parameters.
✅ Example: A decorator that repeats a function multiple times
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()
🔹 Output:
Hello!
Hello!
Hello!
✔ repeat(3) makes say_hello() run three times.
5️⃣ Built-in Decorators: @staticmethod and @classmethod
Python provides built-in decorators for class methods.
✅ @staticmethod (No access to self)
class Math:
@staticmethod
def add(x, y):
return x + y
print(Math.add(5, 3))
✅ @classmethod (Accesses class variables, not instance variables)
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
return cls.count
print(Counter.increment()) # 1
print(Counter.increment()) # 2
6️⃣ Summary
Concept Description
Basic Decorator Modifies function behavior without changing its structure
Custom Decorators Uses *args, **kwargs to work with any function
Multiple Decorators Stacking multiple decorators changes function behavior step by step
Decorator with Arguments A decorator that takes parameters like @repeat(3)
Built-in Decorators @staticmethod, @classmethod for class methods
Date: 2025-03-24 00:00:00.000000