Decorators in Python

 

Decorators in Python 

Python is powerful not just because it is simple, but because it provides advanced features like Decorators and Generators.

If you want to become a strong Python developer, especially for interviews and real-world projects, you must understand these concepts clearly.

In this blog, you will learn:

  • What are Decorators?

  • How Decorators work

  • What are Generators?

  • How Generators improve performance

  • Real-world examples

  • Interview tips

What Are Decorators in Python?

A Decorator is a function that modifies the behavior of another function without changing its actual code.

In simple words:

A decorator adds extra functionality to an existing function.


Why Use Decorators?

Decorators are used for:

  • Logging

  • Authentication

  • Authorization

  • Measuring execution time

  • Input validation

  • Caching

They are widely used in frameworks like:

  • Django

  • Flask


Basic Example of a Decorator

def my_decorator(func):
def wrapper():
print("Something before the function runs")
func()
print("Something after the function runs")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

Output:

Something before the function runs
Hello!
Something after the function runs

How It Works:

  • @my_decorator modifies say_hello

  • The original function is wrapped inside another function


Decorator with Arguments

def decorator(func):
def wrapper(name):
print("Welcome!")
func(name)
print("Goodbye!")
return wrapper

@decorator
def greet(name):
print(f"Hello {name}")

greet("Bency")

Real-World Example: Execution Time Calculator

import time
def calculate_time(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print("Execution time:", end - start)
return wrapper
@calculate_time
def slow_function():
time.sleep(2)
print("Function completed")

slow_function()

This is very useful in real projects.

Comments