Module 14 · Lesson 01
Decorators
Wrap extra behaviour around functions without changing them: functions as objects, closures, the @ syntax, wrappers with *args and **kwargs, functools.wraps, decorators with arguments and stacking.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Functions as values
- Write a first decorator
- Wrappers for any arguments
- Watch a decorator wrap a function
Wrap a function, keep it unchanged
A decorator takes a function and gives back a new one that adds something before or after it.
Functions are values
Store a function in a name, or hand it to another function, like any value.
The wrapper
An inner function calls the original, with extra work around the call.
The @ line
@timerabove adefmeansf = timer(f)straight after it.functools.wraps
Copies the name and docstring, so the wrapped function still looks like itself.
Decorators everywhere
Frameworks use decorators to add behaviour with a single line.
- Web pages
@app.route("/home")tells a web framework which function answers a page. - Caching
@functools.cacheremembers answers, so slow work runs only once. - LoggingWrite a line to a log every time a function is called.
- Sign-in checks
@login_requiredturns away anyone who is not signed in.
The line every wrapper needs
Inside a wrapper, this line calls the original function. Tap each part to see its job.
Part 1 of 4
result:The original's answer. The wrapper should return it, or every call gives None.
Wrap functions with decorators
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Functions are values
A function is an object: give it another name, or pass it to another function.
Your turn: Write a whisper function that lower-cases text, and pass it to apply.
def shout(text):
return text.upper() + "!"
def apply(func, value):
return func(value)
speak = shout
print(speak("hi"))
print(apply(shout, "hey"))
print(apply(len, "hey"))Press Run to see what it prints.Watch a decorator wrap a function
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def bold(func):
- def wrapper(text):
- return "**" + func(text) + "**"
- return wrapper
- def title(text):
- return text.title()
- print(title("hello world"))
- print(title.__name__)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.When does the decorator run?
def deco(func):
print("decorating", func.__name__)
return func
def hi():
print("hi")
print("done")0 of 6 answered
Common decorator misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
import functools
def decorator(func):
@functools.wraps(func) # keep name and docstring
def wrapper(*args, **kwargs):
# before
result = func(*args, **kwargs)
# after
return result # pass the result back
return wrapper
@decorator # same as f = decorator(f)
def f(x): ...
def factory(setting): # decorator with arguments
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
@factory(3) # f = factory(3)(f)
def g(): ...
@outer # stacked: h = outer(inner(h))
@inner
def h(): ...Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Counting and logging calls
Write a decorator that counts how many times a function has been called and prints the count and the result on every call. Apply it to a discount function and check that its name survives.
import functools
def counted(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
result = func(*args, **kwargs)
print(f"call {wrapper.calls}: {func.__name__}{args} -> {result}")
return result
wrapper.calls = 0
return wrapper
@counted
def discount(price, percent):
"""Price after a percentage discount."""
return round(price * (1 - percent / 100), 2)
discount(80, 25)
discount(19.99, 10)
print(discount.__name__, "|", discount.__doc__, "|", discount.calls, "calls")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Forgetting to return the result
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
def logged(func):
def wrapper(*args):
print('calling', func.__name__)
func(*args)
return wrapper
@logged
def square(n):
return n * n
print(square(4))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Web applications
Role checks on web handlers
An internal admin site has many handler functions, and some may only be used by certain roles. Instead of repeating the same if statement at the top of each handler, the team writes one decorator factory and marks each handler with the role it needs.
Why Python fits
The rule lives in one place, and each handler states its requirement in a single readable line. The wrapper checks the role before the handler body ever runs, and
functools.wrapskeeps each handler's real name for the error message. Adding a new protected handler needs no new checking code at all.Pythonimport functools class Forbidden(Exception): pass def requires(role): def decorator(handler): @functools.wraps(handler) def wrapper(user, *args, **kwargs): if role not in user["roles"]: raise Forbidden(f"{user['name']} needs {role} for {handler.__name__}") return handler(user, *args, **kwargs) return wrapper return decorator @requires("admin") def delete_account(user, account_id): return f"account {account_id} deleted by {user['name']}" @requires("support") def view_ticket(user, ticket_id): return f"ticket {ticket_id} shown to {user['name']}" ana = {"name": "ana", "roles": {"admin", "support"}} ben = {"name": "ben", "roles": {"support"}} for call in [lambda: delete_account(ana, 7), lambda: view_ticket(ben, 31), lambda: delete_account(ben, 8)]: try: print(call()) except Forbidden as error: print("403:", error)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
When does the decorator code run?
Can I decorate a method in a class?
How do I undo a decorator to test the original function?
Should I write my own caching decorator?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 23 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.