What Are Python Decorators? See Examples in detail

Python decorators are special functions that modify the behavior of other functions or methods without changing their actual code. They provide a clean and reusable way to add functionality dynamically.

Decorators are widely used for logging, authentication, timing, and validation in Python applications.


Why Decorators Are Important

  • Add functionality to existing code without modifying it
  • Improve code readability and maintainability
  • Enable modular and reusable design
  • Commonly used in web frameworks and APIs

Example:

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

def greet():
    print("Hello, Python!")

greet = decorator(greet)
greet()

Python Decorator Syntax

Python provides a shortcut using the @ symbol.

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def greet():
    print("Hello, Python!")

greet()

Output:

Before function call
Hello, Python!
After function call

Example 1: Logging Function Calls

def log(func):
    def wrapper(*args, **kwargs):
        print(f"Function {func.__name__} called with args {args} and kwargs {kwargs}")
        return func(*args, **kwargs)
    return wrapper

@log
def add(a, b):
    return a + b

print(add(5, 3))

Example 2: Timing Function Execution

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"Execution time: {end - start} seconds")
        return result
    return wrapper

@timer
def compute():
    sum([i**2 for i in range(1000000)])

compute()

Built-in Python Decorators

  • @staticmethod – Defines a static method in a class
  • @classmethod – Defines a class method
  • @property – Allows method to be accessed like an attribute

Example:

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def area(self):
        return 3.14 * self._radius ** 2

c = Circle(5)
print(c.area)

Best Practices

✔ Use decorators for cross-cutting concerns like logging or authentication
✔ Keep decorator logic simple
✔ Use functools.wraps to preserve function metadata
✔ Avoid nesting too many decorators


Conclusion

Decorators in Python are a powerful tool for enhancing or modifying function behavior dynamically. They allow developers to write clean, modular, and reusable code and are widely used in real-world Python applications.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *