# Decorators & Function Wrappers

> Master Python decorators and the @ syntax: wrap and enhance functions dynamically, preserve introspective metadata with functools.wraps, handle arbitrary arguments with *args and **kwargs, and build production timing, authentication, and caching middleware.

Subject: Python | Lesson 24 of 24 | 8 min read
Interactive lesson: https://codewithanimation.in/python/decorators
Previous: [Generators & The Lazy yield Protocol](https://codewithanimation.in/python/generators.md)

## First-Class Functions and the @ Sugar

In Python, functions are first-class objects: they can be passed as arguments, assigned to variables, defined inside other functions, and returned from function calls.

A decorator is simply a function that accepts another function as an argument, wraps it with additional behavior, and returns the modified wrapper function.

The `@decorator_name` syntax placed above a function definition is syntactic sugar. Writing `@my_decorator def greet(): pass` is exactly equivalent to `def greet(): pass; greet = my_decorator(greet)`.

## DRY Cross-Cutting Concerns: Timing, Auth, and Caching

In enterprise codebases, certain behaviors must be applied across dozens of different functions: logging call arguments, timing performance, verifying user authentication tokens, validating inputs, or caching return values.

Copying boilerplate checks into every function clutters domain business logic and invites bugs when requirements shift.

Decorators isolate cross-cutting concerns into clean, reusable modules. The core function focuses solely on its business responsibility, while decorators handle infrastructure concerns transparently.

## The Universal Wrapper Anatomy and functools.wraps

A production decorator accepts the target function, defines an inner `wrapper(*args, **kwargs)` function that intercepts calls with arbitrary arguments, and returns that inner wrapper.

Crucially, always decorate the inner wrapper with `@functools.wraps(fn)`. This automatically copies over the original function's `__name__`, `__doc__`, and signature metadata.

Inside the wrapper, record state before calling `result = fn(*args, **kwargs)`, perform post-execution actions (like measuring elapsed time), and return `result` to the caller.

## Common mistake: The Lost Identity Trap: Forgetting @functools.wraps

If you omit `@functools.wraps(fn)`, the returned wrapper function replaces your original function's identity. Calling `my_func.__name__` returns `'wrapper'` instead of `'my_func'`, and help docstrings vanish completely.

This identity loss breaks logging frameworks, API auto-documentation tools (like FastAPI and Swagger), and debugging stack traces.

Always include `import functools` and decorate your inner wrapper with `@functools.wraps(fn)` as standard discipline.

## Tip: Stacking Decorators: Bottom-to-Top Evaluation

When stacking multiple decorators above a function, they are applied from bottom to top. For example, `@auth_required` placed above `@rate_limited` above `def api():` is evaluated as `auth_required(rate_limited(api))`.

The innermost decorator wraps the core function first, and the outermost decorator wraps around the whole composite chain.

## Try it: Interactive Onion-Skin Decorator Chamber

Step through execution of a wrapped function. Watch the execution pointer enter the outer decorator layer, record the start timestamp, call the inner function, compute elapsed execution time, and return the preserved result.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/decorators

## Check yourself

### Question 1

What is `@audit_log def process(data): pass` strictly equivalent to in Python?

- A. process = audit_log(process)
- B. audit_log = process(audit_log)
- C. audit_log.process(data)
- D. process = lambda data: audit_log

Correct answer: A

The @ syntax is pure syntactic sugar: it passes the defined function into the decorator callable and re-binds the function name to whatever callable the decorator returns: 'process = audit_log(process)'.

- Why not B: The decorator takes the original function as an argument, not the reverse.
- Why not C: Decorators wrap functions rather than defining method namespaces.
- Why not D: The decorator call returns the wrapper callable directly.

### Question 2

Why must production decorators decorate their inner wrapper with `@functools.wraps(fn)`?

- A. To preserve the original function's name (__name__), docstrings (__doc__), and parameter signatures
- B. To compile the Python wrapper into C-level bytecode for faster execution
- C. To prevent multiple threads from invoking the wrapper simultaneously
- D. To make the decorated function globally accessible across all modules

Correct answer: A

Without @functools.wraps, the function's __name__ becomes 'wrapper' and all docstrings and annotations are erased. @functools.wraps copies introspective metadata so tooling, debuggers, and doc generators work properly.

- Why not B: functools.wraps preserves introspective metadata, not compilation.
- Why not C: wraps does not provide thread synchronization or locking.
- Why not D: Function scope is unaffected by functools.wraps.

### Question 3

If a function is declared with `@decorator_a` above `@decorator_b`, in what order are the decorators wrapped around the function?

- A. decorator_b wraps the original function first, and then decorator_a wraps around decorator_b
- B. decorator_a wraps the original function first, and then decorator_b wraps around decorator_a
- C. Both decorators execute simultaneously in parallel threads
- D. Python raises a SyntaxError if more than one decorator is stacked

Correct answer: A

Decorators are evaluated from bottom to top: func = decorator_a(decorator_b(func)). Thus decorator_b wraps the core function first, and decorator_a wraps the resulting wrapper.

- Why not B: Decorators are evaluated from bottom to top: func = decorator_a(decorator_b(func)).
- Why not C: Python decorators are applied sequentially at function definition time.
- Why not D: Stacking decorators is standard Python syntax.

## Remember this

- Decorators wrap and enhance functions without altering their underlying source code.
- @decorator syntax is equivalent to target_fn = decorator(target_fn).
- Always apply @functools.wraps(fn) to the inner wrapper to preserve function name, docstring, and annotations.
- Use *args and **kwargs in the wrapper signature so your decorator can wrap any function.
- Stacked decorators execute bottom-up during setup and outside-in during invocation.
