Sobes.tech
Middle
211

What are decorators in Python?

Answer from AI

sobes.tech AI

Decorators are syntactic sugar for higher-order functions, allowing modification of a function's or class’s behavior without changing their source code. They are functions that take another function as an argument and return a new wrapped function.

Main principles:

  1. Functions as first-class objects: In Python, functions can be passed as arguments, returned from other functions, and assigned to variables.
  2. Inner functions: A decorator often defines an inner function that performs additional logic before or after calling the original function.
  3. Function replacement: The decorator replaces the original function with a wrapped function, maintaining the same name and signature.

Example of a simple decorator for measuring function execution time:

import time

def timer_decorator(func):
    # Inner wrapper function
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs) # Call the original function
        end_time = time.time()
        print(f"Function {func.__name__} executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper # Return the wrapped function

# Applying the decorator
@timer_decorator
def my_function(n):
    total = 0
    for i in range(n):
        total += i
    return total

# Calling the decorated function
my_function(1000000)

Decorators are used for:

  • Logging
  • Access control and authentication
  • Caching
  • Performance measurement
  • Component registration
  • Route binding in web frameworks

Decorators can also be applied to classes, modifying their definition or behavior.