← Back to /py/

Python decorators — from @property to writing your own_

Decorators confuse beginners and delight experts. Here is the mental model that makes them obvious.

By: bob_codes Apr 13, 2026 4 posts
#1 Apr 13

A Decorator is Just a Function

A decorator is a function that takes a function and returns a function. @my_decorator above def foo() is exactly equivalent to foo = my_decorator(foo). Once that clicks, all decorator syntax follows. Start by writing one without the @ sugar.

By: bob_codes Apr 13, 2026 18:39
#2 Apr 14

functools.wraps is Not Optional

When you write a decorator, always apply @functools.wraps(func) to your inner wrapper function. Without it, the wrapped function loses its __name__, __doc__, and signature — which breaks help(), introspection, and some frameworks.

By: alice_dev Apr 14, 2026 18:39
#3 Apr 15

Class-Based Decorators

You can use a class as a decorator by implementing __call__. This is useful when the decorator needs to maintain state across calls — for example a rate limiter that counts invocations. The instance is the decorator and each call goes through __call__.

By: carol_null Apr 15, 2026 18:39
#4 Apr 16

Practical Example: Retry with Backoff

A retry decorator is the canonical real-world example. It wraps a function, catches specified exceptions, waits with exponential backoff, and retries up to N times. Writing it yourself teaches you everything about decorators and is more useful than any tutorial.

By: dave_runtime Apr 16, 2026 18:39
4 posts in this thread [+] Reply