Decorators
def greet():
return "hello"Start with a plain function: greet() returns 'hello'.
1Level 1 · BasicsBasics
A decorator wraps a function to add extra behaviour, such as timing it, logging calls or checking inputs, without changing the function's own code. You'll see decorators everywhere in real Python, like @dataclass, @property and web frameworks' @app.route.
Step 1: functions are values
In Python a function is an object like any other. You can store it in a variable, pass it to another function, and return it from a function:
def shout(text):
return text.upper()
say = shout # no brackets: the function itself
print(say("hi")) # HI
Step 2: a function that builds a function
A function can define an inner function and return it. The inner function remembers the variables around it; this is called a closure.
Step 3: the decorator
def announce(func):
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
result = func(*args, **kwargs) # run the original
print("Done")
return result
return wrapper
@announce
def add(a, b):
return a + b
@announce above def add is shorthand for add = announce(add). Now every call to add actually runs wrapper, which runs extra code around the original.
*args and **kwargs collect any positional and keyword arguments, so the same decorator works on functions with any parameters.
Keep the function's name: functools.wraps
Without help, the decorated function's name becomes "wrapper". Put @functools.wraps(func) on the wrapper to copy the original name and docstring across. It's good practice in every decorator.
Decorators with arguments
@repeat(3) needs one more layer: a function that takes the argument and returns a decorator. See the last example.
Useful built-in decorators
@functools.lru_cacheremembers results, so slow recursive functions become fast.@propertylets a method be read like an attribute.@staticmethodand@classmethodare for methods that don't need an object.
Key points: functions are values; a decorator takes a function and returns a new one that wraps it;@decomeansf = deco(f); use*args, **kwargsandfunctools.wrapsin the wrapper.
See it in actionThe decorator wraps the function
Calling greet() actually runs wrapper(), which calls the original and changes its result.
Try it yourselfExample 1: Functions are values
Functions can be stored, passed around and returned.
Output appears hereFunctions are values
Fill the blank so say refers to the same function as shout and the program prints HI!.
def shout(text): return text.upper() + "!" say = print(say("hi"))
Example 2: A logging decorator
The wrapper runs before and after the original function.
Output appears hereAnnounce the call
Fill the blanks so the decorator prints Calling add before running the function, then the result 5.
def announce(func): def wrapper(*args): print("Calling", func.__name__) return (*args) return @announce def add(a, b): return a + b print(add(2, 3))
The result disappears
The decorated double(4) should print Running and then 8, but it prints None instead of 8. Fix the wrapper.
Run it twice
Write a decorator twice that calls the function two times. Decorate hello() (which prints Hello) so calling it once prints Hello twice.
Example 3: Timing a function
A reusable timer you can put on any function.
Output appears hereExample 4: Caching with lru_cache
Plain recursive Fibonacci is very slow for n = 35; with the cache it's instant.
Output appears hereFast Fibonacci
Add @lru_cache so fib(80) finishes instantly, then print it: 23416728348467685.
Example 5: A decorator with an argument
repeat(3) returns the actual decorator. That's the extra layer.
Output appears here2Level 2 · IntermediatePractical decorators
Most real decorators follow the same shape: run something before, call the original, run something after.
Counting and validating
A decorator can count how often a function runs, check its arguments, or refuse to run it unless a user is logged in. The original function stays focused on its own job.
Stacking decorators
With two decorators, the one closest to def wraps first. @a above @b means f = a(b(f)).
Retry
For things that sometimes fail (network calls), a @retry(times=3) decorator tries again before giving up.
See it in actionThe wrapper runs around the original
Watch the call go into wrapper first, then into greet, then back out.
Example 6: Stacked decorators and a login check
Swap the order of @count_calls and @require_login and see what changes.
Output appears hereExample 7: Retry a flaky operation
The fake download fails twice, then works on the third try.
Output appears here3Level 3 · AdvancedClass decorators, decorator classes and registries
Registries
A decorator doesn't have to wrap anything. It can just record the function in a dictionary and return it unchanged. Web frameworks use this for routes (@app.get("/home")) and command-line tools for commands.
Decorators that are classes
Any object with __call__ can be a decorator, and a class can keep state neatly in attributes.
Decorating classes
@dataclass is a class decorator: it receives the class, adds methods and returns it. You can write your own, such as one that adds a __repr__.
Method decorators
@functools.cached_property computes a value once per object; @functools.singledispatch picks an implementation by the argument's type.
Example 8: A command registry
Adding a command is just adding a decorated function.
Output appears hereExample 9: Decorator classes, class decorators and singledispatch
Three different shapes of decorator in one program.
Output appears herereturn result makes every decorated function return None. Always return what the original function returned.What does this print?
def double(func):
def wrapper(x):
return func(x) * 2
return wrapper
@double
def add_one(x):
return x + 1
print(add_one(4))50 graded problems are waiting in Topic Practice.