๐ Day 100/150 – Decorator Example in Python
A decorator is a special function in Python that allows you to add extra functionality to another function without modifying its original code. Decorators are commonly used for logging, authentication, timing functions, and more.
In this post, we'll explore four common examples of decorators in Python.
Method 1 – Basic Decorator
Create a simple decorator that prints a message before calling a function.
def decorator(func):
def wrapper():
print("Before the function is called")
func()
return wrapper
@decorator
def greet():
print("Hello, World!")
greet()
Output
Before the function is calledExplanation
decorator() accepts a function as an argument.
wrapper() adds extra functionality before calling the original function.
@decorator applies the decorator to greet().
Calling greet() actually executes wrapper().
Method 2 – Decorator with Function Arguments
Decorators can also work with functions that take parameters.
def decorator(func): def wrapper(name): print("Welcome!") func(name) return wrapper @decorator def greet(name): print("Hello,", name) greet("Alice")
Output
Welcome!
Hello, Alice
Explanation
wrapper(name) accepts the argument passed to greet().
It prints a welcome message before calling the original function.
The original function receives the same argument.
Method 3 – Decorator that Executes Code Before and After
A decorator can execute code both before and after the original function.
def decorator(func):
def wrapper():
print("Starting...")
func()
print("Finished!")
return wrapper
@decorator
def task():
print("Task is running")
task()
Output
Starting...Explanation
The decorator prints "Starting...".
It then calls the original function.
After the function finishes, it prints "Finished!".
This is useful for logging and monitoring function execution.
Method 4 – Taking User Input
Use a decorator with a function that accepts user input.
def decorator(func):
def wrapper(name):
print("Welcome to Python!")
func(name)
return wrapper
@decorator
def greet(name):
print("Hello,", name)
name = input("Enter your name: ")
greet(name)
Sample Input
SamOutput
Welcome to Python!Explanation
The user enters a name.
The decorator displays a welcome message.
The original function greets the user using the entered name.
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Decorator | Understanding how decorators work |
| Decorator with Arguments | Functions that accept parameters |
| Before and After Execution | Logging and monitoring |
| User Input | Interactive programs |
๐ฅ Key Takeaways
A decorator adds extra functionality to a function without changing its original code.
Decorators are created using functions that return another function.
The @decorator syntax is used to apply a decorator.
Decorators can work with functions that have parameters.
They are commonly used for logging, authentication, timing, caching, and validation.
Stay tuned for Day 101 of the #150DaysOfPython series! ๐


