---
title: "What are Python decorators and when are they useful?"  
description: "What are Python decorators and when are they useful?"  
author: "Kacper Jankowski"  
published: 2026-11-15  
updated: 2026-11-15  
canonical: https://www.mindstick.com/forum/163030/what-are-python-decorators-and-when-are-they-useful  
category: "python"  
tags: ["python", "decorators", "functions", "closures", "Advanced Python"]  
reading_time: 1 minute  

---

# What are Python decorators and when are they useful?

I see @something above functions in Flask and Django code. What is it, and can I write my own?

## Replies

### Reply by Laura De Rosa

A decorator takes a function, wraps it with extra behaviour, and returns the new function. The `@name` line above a function is shorthand for `func = name(func)`.

Example: a decorator that times a function:

```
import time
from functools import wraps

def timer(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

@timer
def slow():
    return sum(range(5_000_000))
```

Use `functools.wraps` so the wrapped function keeps its name and docstring.

Typical uses: logging, timing, caching (`functools.lru_cache`), checking login or permissions (`@login_required`) and registering routes (`@app.route`). They keep this cross-cutting code out of your main logic.


---

Original Source: https://www.mindstick.com/forum/163030/what-are-python-decorators-and-when-are-they-useful

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
