logo

What Are Decorators?

Decorators wrap functions to extend or modify their behavior. You've probably seen the @ syntax:

@some_decorator
def my_function():
    pass

This is equivalent to:

def my_function():
    pass
my_function = some_decorator(my_function)

The decorator receives your function, does something with it, and returns a (usually modified) function.

Why use decorators?

  • Add logging, timing, or caching to existing functions
  • Enforce authentication or permissions
  • Register functions with frameworks (Flask routes, pytest fixtures)

Decorators follow the "open-closed principle" - extend behavior without modifying the original code.

I explain decorator fundamentals in my Python Decorators course.