Day 23: Decorators in Python

Day 23: Decorators in Python

Welcome to Day 23 of our Python journey! Today, we're learning a powerful feature of Python: decorators. This enhances the functionality and readability of our code by providing elegant ways to modify behavior or manage resources.

Decorators

In Python, decorators are functions that wrap other functions or methods, allowing you to add functionality to existing code without modifying its structure. Decorators are commonly used for tasks like logging, authentication, caching, and more.

The basic syntax of a decorator involves defining a decorator function and applying it to another function using the @ symbol

Simplified Decorator Concept

At its core, a decorator performs three key tasks:

  1. Accepts a Function: Decorators take a function as their input parameter.

  2. Enhances Functionality: They augment the behavior of the input function by adding extra features or functionality.

  3. Returns a Modified Function: Finally, decorators return a new function, incorporating the additional functionality.

Basic Syntax of Decorator

def my_decorator(func):
    #decorator logic 
    return func

@my_decorator
def my_function():
    pass

In this , @my_decorator is applied to the my_function function. You can define the my_decorator function to perform any custom logic you need, such as logging, authentication, or modifying the behavior of my_function.

Here's how we create a decorator to handle subtraction:

def smart_subtract(func):
    def inner(a, b):
        print("subtracting", b, "from", a)
        return func(a, b)
    return inner

@smart_subtract
def subtract(a, b):
    return a - b

result = subtract(10, 2)
print("Result after subtraction:", result)
  • The smart_subtract decorator takes a function func as its argument and defines an inner function inside it.

  • Inside the inner function, a message is printed indicating the operation about to be performed.

  • The func is called with the provided arguments (a and b), and the result is returned.

  • The subtract function is decorated with @smart_subtract, which means it will be wrapped by the inner function defined in the decorator.

Decorators can also be implemented using classes. This is useful for more complex scenarios where you need to maintain state or perform additional operations.