python · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A wraps extra behaviour around any function.
A decorator is a function that takes a function, wraps it, and returns the wrapped version. The is a closure: it remembers the original, runs some extra code, calls the original and hands back its answer.
Writing @shout on the line above def greet is shorthand for greet = shout(greet). Every call to greet now goes through the wrapper. Give the wrapper *args, **kwargs so it works for any function.
Add @functools.wraps(func) to the wrapper so the decorated function keeps its own name.
import functools
def shout(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper() + "!"
return wrapper
@shout
def greet(name, greeting="hello"):
return f"{greeting}, {name}"
print(greet("sam"), greet("ana", greeting="hi"), greet.__name__) Without functools.wraps, greet.__name__ would say wrapper, which makes error messages confusing.
guess first
Follow every print. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def announce(func):
def wrapper(*args):
print("Starting", func.__name__)
answer = func(*args)
print("Finished", func.__name__)
return answer
return wrapper
@announce
def add(a, b):
return a + b
print(add(2, 3))
your turn
Your turn. Guard a function against empty text.
Put the decorator on shout in the first blank, with its @. In the second, type any word you like.
fix it
The decorator breaks the function. Fix it!
- The error says
NoneTypeis not callable. What didloggedhand back to replacearea? loggedbuilds a wrapper but never returns it, so it hands backNone.- Add
return wrapperat the end oflogged, lined up withdef wrapper, then run.
nailed it
you can wrap any function in new powers. :D
- A decorator takes a function and returns a wrapped one.
@nameabovedefmeansfunc = name(func).- Use
*args, **kwargsandfunctools.wrapsin every wrapper.
new words in your collection
- decorator
- wrapper
This lesson isn’t saved. A free account remembers every lesson you finish.