Decorators and logging, the language features behind @app.route.
Open the interactive lessons →Python Fundamentals past questions
Contents
- Functions are values
- What @decorator does
- Wrapper patterns: before, after, change, repeat
- Stacked decorators
- Logging levels, format and sys.argv
1. Functions are values
A function name is a label on an object; you can hand that object to other functions.
passing functions around, returning them, and closures
The question this lesson answers. What is the difference between greet and greet()? Everything about decorators, and much of Flask, rests on this one difference.
In Python, def greet(): ... creates a function object and puts the label greet on it. Writing greet without brackets refers to the object; writing greet() calls it. Because a function is an object, you can store it in another name, pass it to another function, or return it from a function.
A function is like a recipe card. greet is the card; greet() is cooking from it. You can hand the card to someone else (pass it), or someone can give you a new card (return it). The analogy breaks in one place: a card returned from inside another function can remember values from where it was written (a closure).
Three things that look alike
| You write | What happens | What you get |
|---|---|---|
greet | nothing runs | the function itself |
greet() | the body runs now | whatever it returns |
return greet | nothing runs | the function is handed to the caller |
Step 1: pass a function to another function. The receiver decides when to call it, and how many times.
values.py
def twice(f, x):
return f(f(x))
def add3(n):
return n + 3
print(twice(add3, 10))
Worked example: Passing a function
Problem.
Using twice and add3 above, what does print(twice(add3, 0)) show?
Idea.
twice applies f two times.
twice(add3, 0)returnsadd3(add3(0)).- Inner:
add3(0) = 3. - Outer:
add3(3) = 6, which is printed.
Answer.
6
Common mistake.
Answering 3 (applying it once).
Step 2: build a function inside a function. Press Next and watch what each new function remembers.
A closure is an inner function that remembers variables of the function it was made in, even after that outer function has returned. Every decorator's wrapper is a closure: it remembers func, the function it wraps.
A function that returns a function
def make_adder(k):
def add(n):
return n + k
return add
add5 = make_adder(5)
print(add5(10))
A decorator's wrapper is exactly such an inner function. The thing it remembers is the original function.
Worked example: Brackets or no brackets
Problem.
What do print(make_adder(2)(3)) and print(make_adder(2)) show?
Idea.
make_adder(2) returns a function; adding (3) calls it.
make_adder(2)returns the inneraddwithk = 2.make_adder(2)(3)calls it:3 + 2 = 5.print(make_adder(2))prints the function object itself, shown as<function make_adder.<locals>.add at 0x...>(the address varies).
Answer.
5, then a <function ...add ...> description
Common mistake.
Expecting a number from make_adder(2) alone.
return add hands back the function; return add() would call it and hand back its result. Decorators always use the first form: return wrapper.
When does decorator code run? Two moments matter. The decorator's own body runs once, when the def runs (at import). The wrapper's body runs every time the function is called. Exam questions that print inside both places test exactly this difference.
def announce(f):
print("decorating", f.__name__)
return f
@announce
def a():
print("a runs")
print("defined")
a()
Closures: functions that remember. A function defined inside another function can use the outer function's variables, even after the outer one has returned. This is what lets a decorator's wrapper still call f later: the wrapper remembers it. Each call of the outer function makes a fresh inner function with its own memory.
def make_adder(n):
def add(x):
return x + n
return add
add5 = make_adder(5)
add9 = make_adder(9)
print(add5(1), add9(1)) # 6 10
A closure remembers the variable, not its value at that moment. [lambda: i for i in range(3)] makes three functions that all read the same i, which ends at 2, so calling them gives [2, 2, 2].
Worked example: Functions kept in a list
Problem.
What is printed?
Idea.
Work from the innermost call outwards.
ops[0]isabs, soops[0](-3)is 3.ops[1]isstr, so the result becomes the text "3".- Adding "!" joins two strings.
Answer.
3!
Common mistake.
Thinking the list holds results. It holds the functions themselves.
Classes in one example. A class is a mould for objects. __init__ runs automatically when an object is created, and self is that new object. __str__ runs when the object is printed or passed to str(), and it must return a string.
A class with __init__ and __str__
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
b = Book("Flask", 90)
print(b) # Flask (90 pages)
print(b.pages) # 90
| You write | Python calls | Without __str__ |
|---|---|---|
Book("Flask", 90) | __init__ | no difference |
print(b) or str(b) | __str__ | a default text showing the class name and a memory address |
- Look for brackets:
fhands over the function,f()runs it. - A function without
returngivesNone. - Keep a list of what each name points to as you read the code.
No brackets: the thing. Brackets: run it.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Mark every name that has brackets: only those run. |
| 2 | For a returned inner function, note which outer values it remembers. |
| 3 | Evaluate calls from the inside out. |
| 4 | Write a line of output only for a print that runs. |
2. What @decorator does
@d swaps your function for whatever d hands back.
the meaning of the @ line and which code runs on a call
The question this lesson answers. You call greet, yet different code runs. Why? Because the @ line replaced what the name points to.
Callers still dial the same number, but a receptionist now answers and decides whether to put them through. The number is the name, the receptionist is the wrapper, and the person behind is the original. Where the picture stops: the swap happens once, when the code is first read.
@d written above def f means: define f, then immediately run f = d(f). This happens once, when Python reads the definition. After that, the name f refers to whatever d returned.
One line, written two ways
With @ | Without @ |
|---|---|
@shout above def greet | def greet ... followed by greet = shout(greet) |
the usual shape
def shout(func):
def wrapper(name):
return func(name).upper()
return wrapper
@shout
def greet(name):
return "hi " + name
print(greet("ram"))
Step by step: which line prints first? The numbers inside the strings show the order. Predict each one before pressing Next.
If the wrapper never calls func, the original body never runs: none of its prints happen and its return value is never used. Many PYQs hide the real computation in the wrapper and put a distracting body in the original.
Worked example: A wrapper that ignores the original
Problem.
With modify and triple above, what is printed?
Idea.
Rebind triple = modify(triple), then trace only the wrapper.
@modifymakestriplemeanwrapper.triple(2)runswrapper(2).- The wrapper returns
2 * 10 = 20;funcis never called.
Answer.
20
Common mistake.
Answering 6, or 60.
Worked example: A list built only by the wrapper
Problem.
Trace the code below.
Idea.
Only the wrapper runs; it builds squares for i from 0 to N - 1.
funcnow nameswrapper; the original (N + 100) never runs.wrapper(4):itakes 0, 1, 2, 3.- Squares: 0, 1, 4, 9.
Answer.
[0, 1, 4, 9]
Common mistake.
Answering 104 from the original body.
Worked example: The wrapper that forgets to return
Problem.
What are the two printed lines?
Idea.
A function with no return gives back None.
hello()runswrapper.wrappercalls the original, which printshi.- The wrapper drops the result and returns nothing.
- So the outer
printshowsNone.
Answer.
hi then None
Common mistake.
Assuming the original's value passes through by itself.
Decorators that take arguments. @repeat(3) has brackets, so Python first calls repeat(3). That call must return the real decorator, which then receives the function. So a decorator with arguments has three layers: the outer function takes the arguments, the middle one takes the function, the inner one is the wrapper.
def repeat(n):
def deco(f):
def wrapper():
for _ in range(n):
f()
return wrapper
return deco
@repeat(3)
def hi():
print("hi")
hi() # hi hi hi
Worked example: Brackets or not?
Problem.
@repeat (no brackets) is placed above def hi(), with repeat as above.
Idea.
Without brackets, repeat receives the function as n.
- Python runs hi = repeat(hi).
- repeat returns deco, so hi is now deco.
- Calling hi() fails: deco needs an argument.
Answer.
hi becomes the inner deco function; hi() raises TypeError
Common mistake.
Forgetting that @name and @name(...) call different things.
- Rewrite
@dasf = d(f)before tracing. - Separate prints that run at decoration time from prints that run at call time.
- Check that the wrapper returns the result, otherwise the caller gets
None.
Decorate once, wrap every time.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Rewrite @d as f = d(f). |
| 2 | Run the decorator's own body: it happens at definition. |
| 3 | On each call, run the wrapper. |
| 4 | Run the original only on a line where the wrapper calls it. |
3. Wrapper patterns: before, after, change, repeat
Read the wrapper line by line; the original runs only where it is called.
the common shapes a wrapper takes and the output each one produces
The question this lesson answers. Given a wrapper you have never seen, how do you write its output without guessing? Read it top to bottom and leave it only where it calls the original.
Whatever the wrapper does before the call is the bread underneath, the call is the filling, and what it does afterwards is the bread on top. Some wrappers have two fillings, and some have none at all.
Four wrapper shapes
| Shape | Wrapper body | Effect |
|---|---|---|
| before / after | print(...); r = func(x); print(...); return r | prints around the call; the result is unchanged |
| change the result | return func(a, b) ** 2 | the caller gets a transformed value |
| call twice | r1 = func(); r2 = func(); return r1, r2 | the body runs twice; a tuple comes back |
| never call | return something_else | the original is dead code |
Two questions settle every wrapper: how many times does it call the original, and what does it return?
Read the wrapper like this
| Question | Where to look | If you skip it |
|---|---|---|
| How many calls? | count func(...) lines | you miss repeated output |
| What comes back? | the wrapper's return | you print a value instead of None, or the reverse |
before and after
def log(func):
def wrapper(x):
print("in")
r = func(x)
print("out")
return r
return wrapper
@log
def inc(x):
print("work")
return x + 1
print(inc(1))
Watch a double call. Notice that the original's print appears once for each call, and nothing is returned to the screen until the end.
Worked example: Change the result
Problem.
The wrapper returns func(p, q) + 5; the original bar(a, b) returns a * b. What does print(bar(4, 5)) show?
Idea.
Original first, then the wrapper's change.
bar(4, 5)runswrapper(4, 5).func(4, 5)is the original:4 * 5 = 20.- The wrapper adds 5:
25.
Answer.
25
Common mistake.
Answering 20 or 45.
Worked example: Calling twice
Problem.
What does the code below print?
Idea.
The wrapper prints once, calls the original twice, and returns a tuple.
ping()runswrapper(): it printsstart.func()returnspongtwice; nothing else prints (the original only returns).- The wrapper returns the tuple
('pong', 'pong'), which the outerprintshows.
Answer.
start then ('pong', 'pong')
Common mistake.
Printing pong on separate lines: the original returns, it does not print.
Write the output column by column: a line appears only for each print that actually runs. A return adds no line until something prints it.
Worked example: Prints a value, returns nothing
Problem.
What are the two printed lines?
Idea.
Printing a value is different from returning it.
- The wrapper stores
f(4), which is 5. - It prints
got 5. - It has no
return. - The outer
printtherefore showsNone.
Answer.
got 5 then None
Common mistake.
Writing 5 as the second line.
Keeping the function's name: functools.wraps. A plain wrapper replaces the function, so greet.__name__ becomes "wrapper". This matters in Flask: Flask names each view by its function name, so two views decorated by the same plain wrapper both become "wrapper" and the app refuses to start. Putting @functools.wraps(f) on the wrapper copies the original name across.
A wrapper with and without wraps
| Plain wrapper | With @functools.wraps(f) | |
|---|---|---|
f.__name__ | "wrapper" | the original name |
| Two Flask views wrapped | AssertionError: endpoint "wrapper" overwritten | both views work |
def count(f):
def wrapper(*a):
wrapper.calls += 1
return f(*a)
wrapper.calls = 0
return wrapper
@count
def sq(x):
return x * x
sq(2); sq(3)
print(sq.calls, sq(4)) # 2 16
Why wrappers take *args and **kwargs. A decorator does not know what arguments the function it wraps will need. *args collects every positional argument into a tuple and **kwargs collects every keyword argument into a dict; calling f(*args, **kwargs) passes them all on unchanged. That is why one wrapper fits any function.
What arrives in the wrapper
| Call | args | kwargs |
|---|---|---|
show(1, 2, a=3) | (1, 2) | {'a': 3} |
show() | () | {} |
show(*[4, 5], **{'b': 6}) | (4, 5) | {'b': 6} |
Worked example: A wrapper that drops arguments
Problem.
def wrapper(): return f() wraps def add(a, b): return a + b. Then add(2, 3) is called.
Idea.
The wrapper accepts no arguments.
- add now names the wrapper.
- wrapper() takes 0 arguments but 2 were given: TypeError.
Answer.
TypeError
Common mistake.
Expecting 5: the wrapper must accept and pass on args, *kwargs.
Count the calls, then find the return.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Start at the first line of the wrapper. |
| 2 | At each func(...), run the original completely, then come back. |
| 3 | Keep returned values in your head; they print nothing. |
| 4 | Apply the wrapper's return last. |
4. Stacked decorators
The decorator nearest the function wraps it first; on a call, the outer one starts first.
two or more @ lines above one function
The question this lesson answers. A function has two @ lines above it. Which one acts first? Most people answer "the top one", and that is only half true. By the end you will be able to predict every printed line.
@d above def f means f = d(f). The decorator receives the function and returns a replacement, usually a wrapper that calls the original.
You wrap the gift in blue paper, then put red paper around that. Blue went on first because it is nearest the gift. Whoever opens it meets red first. Where the picture stops: opening happens once, but a wrapper runs again on every call, both on the way in and on the way out.
Step 1: turn the stack into one line. Read the @ lines from the bottom upwards, each one wrapping what you already have.
Building the line, one decorator at a time
| After applying | You have |
|---|---|
| nothing yet | core |
the lower line, @b | b(core) |
the upper line, @a | a(b(core)) |
def a(f):
def w():
return "a(" + f() + ")"
return w
def b(f):
def w():
return "b(" + f() + ")"
return w
@a
@b
def core():
return "x"
print(core())
How to read the picture. To call the function you must enter from outside, so a starts first. The original sits in the centre. A returned value travels outwards, so b touches it before a does.
Step 2: separate two moments. Almost every mistake here comes from mixing them up.
Two different moments
| Definition time | Call time | |
|---|---|---|
| When | once, as Python reads the def | every time the function is called |
| What runs | the decorator functions themselves | the wrapper functions |
| Order | bottom to top | top wrapper starts first |
Step 3: watch one call, line by line. Press Next. Before each step, say what will be printed.
wa cannot finish until wb returns, and wb cannot finish until the original returns. Whoever started last finishes first. So the "before" lines read a, b and the "after" lines read b, a.
Worked example: Two string decorators
Problem.
With a, b and core above, swap the two @ lines (@b above @a). What is printed?
Idea.
Now core = b(a(core)).
ais nearest the function, so it wraps first:a(x).bwraps that result:b(a(x)).
Answer.
b(a(x))
Common mistake.
Keeping the old order.
Worked example: Order changes the number
Problem.
double multiplies the result by 2 and add1 adds 1. f returns 3. What does f() give with @double above @add1, and with the order swapped?
Idea.
The lower decorator changes the result first.
- First order:
f = double(add1(f)). - The result is $(3+1)\times2=8$.
- Swapped:
f = add1(double(f)). - The result is $3\times2+1=7$.
Answer.
8, then 7.
Common mistake.
Reading the stack from the top as the first change to the result.
lambda, map and [::-1]: three short forms wrappers use. lambda x: x / 2 is a function with no name: it takes x and returns x / 2. map(f, items) calls f on every item, in order. map does not give a list by itself, so wrap it in list(...). The slice items[::-1] is a reversed copy.
One value at a time
nums = [1, 4, 9]
halves = list(map(lambda x: x / 2, nums))
print(halves) # [0.5, 2.0, 4.5]
print(halves[::-1]) # [4.5, 2.0, 0.5]
print(nums) # [1, 4, 9]
/ always gives a float8 / 2 is 4.0, not 4. So a list that went through x / 2 prints with decimal points.
Worked example: Reverse after halving
Problem.
Trace the code below.
Idea.
squares = rev(half(squares)): square, then halve, then reverse.
- Original:
[4, 16, 36]. half(inner) divides each by 2:[2.0, 8.0, 18.0](division always gives floats).rev(outer) reverses:[18.0, 8.0, 2.0].
Answer.
[18.0, 8.0, 2.0]
Common mistake.
Reversing before halving, or writing 2 instead of 2.0.
Changing the value or changing the input? Check where the wrapper does its work. If it changes the result (f(n) + 1), the inner decorator acts first. If it changes the argument before calling (f(name.upper())), the outer decorator acts first, because the argument travels inwards.
The direction of travel
| The wrapper edits | Travels | Acts first |
|---|---|---|
the argument, before calling f | inwards | outer (top) decorator |
the result, after calling f | outwards | inner (bottom) decorator |
Worked example: Editing the input
Problem.
@hi is above @upper. What is printed, and what changes if the two lines are swapped?
Idea.
The argument passes through the outer wrapper first.
- The call enters
hifirst, which addsji:ram ji. - Then
upperreceives it:RAM JI. - The original returns
Hello RAM JI. - Swapped:
upperacts first, givingRAM, thenhiaddsjiin small letters.
Answer.
Hello RAM JI, and after swapping Hello RAM ji.
Common mistake.
Using the result rule, inner first, on a wrapper that edits the argument.
Stacking with Flask. @app.route must be the top decorator. Decorators apply from the bottom up, so the route then registers the already-wrapped function, and the wrapper (a login check, say) runs on every request. If @app.route were below the wrapper, Flask would register the bare function and the check would never run.
Order of application and of running
| Written | Applied (at def) | Runs (on a call) |
|---|---|---|
@a then @b above def f | f = a(b(f)) | a's wrapper first, then b's, then f |
@app.route("/x") then @login_required | route registers login_required(f) | the login check runs on each request |
- Build from the bottom decorator upward; run from the top wrapper inward.
- Write the expression
a(b(f))and evaluate it from the inside. - Use brackets in the arithmetic to show which wrapper changes the value first.
With @a above @b above def f, Python builds f = a(b(f)). The decorator nearest the def is applied first and ends up inside. The top one is applied last and ends up outside.
Wrap from the bottom. Enter from the top. Leave from the bottom.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Write the one-line form, such as a(b(f)). |
| 2 | Mark what each wrapper does before calling f and after it. |
| 3 | Walk inwards, doing the before parts from the outside. |
| 4 | Run the original once. |
| 5 | Walk outwards, doing the after parts from the inside. |
5. Logging levels, format and sys.argv
A message prints only if its level is at least the threshold; arguments arrive as strings.
which logging calls print, in what format, and how sys.argv feeds them
The question this lesson answers. Five logging calls run, but only some lines appear. Which, and in what shape? Two settings decide: the level and the format.
Each message has a loudness number. The threshold is the knob: anything quieter than the setting is not heard. Where the picture stops: a message exactly at the setting is heard.
The five levels
| Level | Number | Function |
|---|---|---|
| DEBUG | 10 | logging.debug |
| INFO | 20 | logging.info |
| WARNING | 30 | logging.warning |
| ERROR | 40 | logging.error |
| CRITICAL | 50 | logging.critical |
Step 1: compare two numbers. A message prints when its number is greater than or equal to the threshold's number.
logging.basicConfig(level=X) sets the threshold: a message prints only if its level number is at least X's. Without level=, the threshold is WARNING. Messages go to the terminal (standard error).
log.py
import logging
import sys
logging.basicConfig(level=logging.INFO,
format="%(levelname)s - %(message)s")
a = int(sys.argv[1])
logging.debug("start")
logging.info(f"got {a}")
logging.warning("done")
Format strings
| format | example line |
|---|---|
| (default, no format) | WARNING:root:done |
%(levelname)s - %(message)s | WARNING - done |
%(levelname)s:%(message)s | WARNING:done (no space) |
sys.argv is the list of words on the command line. For python log.py 25 5 it is ['log.py', '25', '5']: index 0 is the file, and every item is a string.
Step 2: command-line words are text. Nothing converts them for you.
python add.py 2 3
| Expression | Result | Why |
|---|---|---|
a + b | 23 | joins two strings |
a * 2 | 22 | repeats a string |
int(a) + int(b) | 5 | numbers after conversion |
Worked example: Which lines print
Problem.
With basicConfig(level=logging.WARNING) (default format), the code calls debug("d"), info("i"), warning("w"), error("e"). What prints?
Idea.
Keep WARNING and above; default format LEVEL:root:message.
- DEBUG and INFO are below WARNING: dropped.
warningprintsWARNING:root:w.errorprintsERROR:root:e.
Answer.
WARNING:root:w then ERROR:root:e
Common mistake.
Printing every call that is reached.
Worked example: A branch that reaches DEBUG
Problem.
Trace python div.py 9 3.
Idea.
The branch taken reaches debug, which is below the threshold.
a = 9,b = 3.info("checking")printsINFO - checking.9 % 3 == 0, so theifbranch callsdebug, which is below INFO: nothing printed.- The
elsebranch does not run.
Answer.
Only INFO - checking
Common mistake.
Adding a DEBUG line because the branch was taken.
Logging defaults you must know. With no setup, the threshold is WARNING and each line looks like WARNING:root:message (level, logger name, message). logging.basicConfig(...) sets level and format, but only the first call counts: a second call is ignored. sys.argv[0] is the script's own name; the arguments follow, as strings.
What is printed
| Code | Output |
|---|---|
logging.debug('d'); logging.info('i'); logging.warning('w') | WARNING:root:w |
basicConfig(level=INFO) then basicConfig(level=DEBUG), then debug and info | INFO:root:i (the second call is ignored) |
basicConfig(format='%(levelname)s - %(message)s'); logging.error('e') | ERROR - e |
python main.py 2 3: argv[0], argv[1] + argv[2], int(...) + int(...) | main.py 23 5 |
Worked example: Two basicConfig calls
Problem.
logging.basicConfig(level=logging.INFO) then logging.basicConfig(level=logging.DEBUG), then logging.debug('d') and logging.info('i').
Idea.
Only the first basicConfig takes effect.
- The threshold stays INFO.
- debug is below INFO: hidden.
- info prints with the default format.
Answer.
INFO:root:i
Common mistake.
Assuming the later call wins and printing the debug line too.
Loggers, handlers and two levels. Real apps use a named logger, logging.getLogger('shop'), instead of the root logger. A message must pass two filters: the logger's level, then each handler's level. A handler decides where messages go (the screen, a file) and how they look (its Formatter).
log = logging.getLogger("shop")
log.setLevel(logging.DEBUG)
h1 = logging.StreamHandler(sys.stdout)
h1.setLevel(logging.WARNING)
h1.setFormatter(logging.Formatter("OUT %(name)s %(levelname)s %(message)s"))
log.addHandler(h1)
log.info("stock checked") # passes the logger, stopped by the handler
log.warning("low stock") # OUT shop WARNING low stock
Level numbers
| Level | Number |
|---|---|
| DEBUG | 10 |
| INFO | 20 |
| WARNING | 30 |
| ERROR | 40 |
| CRITICAL | 50 |
Worked example: print is not logging
Problem.
With level=logging.ERROR, a program runs logging.warning("w") and then print("p"). What appears?
Idea.
The threshold affects logging calls only.
- The warning is below ERROR, so it is dropped.
printignores logging settings.
Answer.
Only p.
Common mistake.
Hiding the print as well.
- First find the threshold, then cross out every call below it.
- Copy the format string literally, including spaces and colons.
- Arguments from
sys.argvare strings, andsys.argv[0]is the script name.
Print if the message is at least the threshold. Arguments arrive as text.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the threshold: the level given, otherwise WARNING. |
| 2 | Compare each call's level with it. |
| 3 | Shape each surviving line with the format. |
| 4 | Check every sys.argv value for int(...) before doing arithmetic. |