DEV Community

Cover image for Understanding python Decorators
Khalil Habib Shariff
Khalil Habib Shariff

Posted on

Understanding python Decorators

Understand Python Decorators: A Twist on Functions

Have you ever encountered the @ symbol used with functions in Python and wondered what it meant? That's the magic of decorators, a unique concept that adds functionality to existing functions without altering their original code.

So, what are decorators?

Imagine wrapping a present. The present itself (the function) remains unchanged, but the wrapping (the decorator) adds something extra – maybe a bow or a ribbon. Similarly, a decorator "wraps" a function, adding new features or modifying its behavior.
Let's see an example:

import time

def timer(func):
    #Decorator that logs the execution time of a function.

    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute.")
        return result

    return wrapper

@timer
def my_function(a, b):
    #This function does some calculations.
    return a * b + 5

result = my_function(3, 4)
print(result) # Output: my_function took 0.00 seconds to execute.
Enter fullscreen mode Exit fullscreen mode

Here, the timer decorator is a function that takes another function (func) as its argument. It then defines an inner function (wrapper) that executes the original function (func) and logs its execution time. Finally, the decorator returns the wrapper function, which replaces the original one.

Benefits of using decorators:
Code Reusability: You can create reusable decorators for common tasks like logging, authentication, or caching, avoiding repetitive code.

Maintainability: Code becomes cleaner and easier to understand by separating concerns (core functionality and additional features).

Flexibility: You can easily add or remove functionalities using decorators without modifying the original function code.

Decorators are versatile and can be used for various purposes:
Such AS:
-Logging, Authentication, Caching, Validation

Remember, decorators add a unique twist to functions in Python, making them a powerful tool for writing clean, maintainable, and feature-rich code. So, embrace the fun and start decorating your functions today.

Top comments (0)