Cover Image for Python Decorator
225 views

Python Decorator

The Python, a decorator is a special type of function that can be used to modify or extend the behavior of another function or method without changing its source code. Decorators are often used for tasks such as logging, authentication, caching, and access control. They are applied using the “@” symbol followed by the decorator function’s name just above the function or method definition. Here’s how decorators work and how to create and use them:

Basic Structure of a Decorator:

A decorator is a higher-order function that takes a function as its argument, performs some processing, and returns a new function or modifies the original function. It typically follows this structure:

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        # Perform some actions before calling the original function
        result = original_function(*args, **kwargs)
        # Perform some actions after calling the original function
        return result
    return wrapper_function

Applying a Decorator:

To apply a decorator to a function, you use the “@” symbol followed by the decorator function’s name just before the function definition. Here’s an example of a simple decorator that measures the execution time of a function:

import time

# Decorator function
def timing_decorator(original_function):
    def wrapper_function(*args, **kwargs):
        start_time = time.time()
        result = original_function(*args, **kwargs)
        end_time = time.time()
        print(f"{original_function.__name__} took {end_time - start_time} seconds to execute.")
        return result
    return wrapper_function

# Apply the decorator to a function
@timing_decorator
def slow_function():
    time.sleep(2)

slow_function()

In this example, the timing_decorator measures the time taken to execute the slow_function and prints the result.

Common Use Cases for Decorators:

  1. Logging: Decorators can log function calls, parameters, and return values for debugging and monitoring.
  2. Authentication and Authorization: Decorators can check user permissions and authentication status before allowing access to specific functions or routes in web applications.
  3. Caching: Decorators can cache the results of expensive function calls to improve performance.
  4. Validation: Decorators can validate input arguments and return values of functions.
  5. Instrumentation: Decorators can be used to collect performance metrics, such as execution time or resource usage.
  6. Retry Mechanism: Decorators can retry a function call if it fails, with optional back-off and error handling.
  7. Function Wrapping: Decorators can wrap functions with additional behavior, such as adding a retry mechanism, rate limiting, or circuit breaking.

Decorators provide a powerful way to add functionality to your code in a clean and modular manner. Python itself includes several built-in decorators, such as @staticmethod, @classmethod, and @property, which are commonly used with classes. You can also create custom decorators to tailor your code to your specific needs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS