10.2 Decorators

10.2 Decorators

Learning decorators to dynamically modify or extend the functionality of functions without changing their code.

A decorator is a function that takes another function as an argument, adds some functionality by "wrapping" it, and returns the new, modified function. This allows you to extend the behavior of a function without permanently changing its source code. The syntax with the `@` symbol (e.g., `@my_decorator`) is "syntactic sugar" that makes the code cleaner. It is equivalent to writing: `my_function = my_decorator(my_function)`.
# Logging Decorator Example
import time

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        return result
    return wrapper

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

add(10, 5)

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.