Python Fundamentals

Decorators and logging, the language features behind @app.route.

5 lessons · 11 past questions · 37.5 marks in the papers collected here

Open the interactive lessons →Python Fundamentals past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Functions are values
  2. What @decorator does
  3. Wrapper patterns: before, after, change, repeat
  4. Stacked decorators
  5. 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.

Picture it

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 writeWhat happensWhat you get
greetnothing runsthe function itself
greet()the body runs nowwhatever it returns
return greetnothing runsthe 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.

  1. twice(add3, 0) returns add3(add3(0)).
  2. Inner: add3(0) = 3.
  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.

Closure

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))
Why this matters next

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.

  1. make_adder(2) returns the inner add with k = 2.
  2. make_adder(2)(3) calls it: 3 + 2 = 5.
  3. 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.

Notice

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
Trap

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.

  1. ops[0] is abs, so ops[0](-3) is 3.
  2. ops[1] is str, so the result becomes the text "3".
  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 writePython callsWithout __str__
Book("Flask", 90)__init__no difference
print(b) or str(b)__str__a default text showing the class name and a memory address
Tips and tricks
  • Look for brackets: f hands over the function, f() runs it.
  • A function without return gives None.
  • Keep a list of what each name points to as you read the code.
Memory line

No brackets: the thing. Brackets: run it.

Method for any exam question

StepDo this
1Mark every name that has brackets: only those run.
2For a returned inner function, note which outer values it remembers.
3Evaluate calls from the inside out.
4Write 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.

A receptionist takes over the phone

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.

The @ line

@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 greetdef 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.

Dead original

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.

  1. @modify makes triple mean wrapper.
  2. triple(2) runs wrapper(2).
  3. The wrapper returns 2 * 10 = 20; func is 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.

  1. func now names wrapper; the original (N + 100) never runs.
  2. wrapper(4): i takes 0, 1, 2, 3.
  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.

  1. hello() runs wrapper.
  2. wrapper calls the original, which prints hi.
  3. The wrapper drops the result and returns nothing.
  4. So the outer print shows None.

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.

  1. Python runs hi = repeat(hi).
  2. repeat returns deco, so hi is now deco.
  3. 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.

Tips and tricks
  • Rewrite @d as f = 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.
Memory line

Decorate once, wrap every time.

Method for any exam question

StepDo this
1Rewrite @d as f = d(f).
2Run the decorator's own body: it happens at definition.
3On each call, run the wrapper.
4Run 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.

A sandwich around a call

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

ShapeWrapper bodyEffect
before / afterprint(...); r = func(x); print(...); return rprints around the call; the result is unchanged
change the resultreturn func(a, b) ** 2the caller gets a transformed value
call twicer1 = func(); r2 = func(); return r1, r2the body runs twice; a tuple comes back
never callreturn something_elsethe 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

QuestionWhere to lookIf you skip it
How many calls?count func(...) linesyou miss repeated output
What comes back?the wrapper's returnyou 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.

  1. bar(4, 5) runs wrapper(4, 5).
  2. func(4, 5) is the original: 4 * 5 = 20.
  3. 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.

  1. ping() runs wrapper(): it prints start.
  2. func() returns pong twice; nothing else prints (the original only returns).
  3. The wrapper returns the tuple ('pong', 'pong'), which the outer print shows.

Answer.

start then ('pong', 'pong')

Common mistake.

Printing pong on separate lines: the original returns, it does not print.

Exam tip

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.

  1. The wrapper stores f(4), which is 5.
  2. It prints got 5.
  3. It has no return.
  4. The outer print therefore shows None.

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 wrapperWith @functools.wraps(f)
f.__name__"wrapper"the original name
Two Flask views wrappedAssertionError: endpoint "wrapper" overwrittenboth 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

Callargskwargs
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.

  1. add now names the wrapper.
  2. wrapper() takes 0 arguments but 2 were given: TypeError.

Answer.

TypeError

Common mistake.

Expecting 5: the wrapper must accept and pass on args, *kwargs.

Memory line

Count the calls, then find the return.

Method for any exam question

StepDo this
1Start at the first line of the wrapper.
2At each func(...), run the original completely, then come back.
3Keep returned values in your head; they print nothing.
4Apply 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.

One fact you need from the last lesson

@d above def f means f = d(f). The decorator receives the function and returns a replacement, usually a wrapper that calls the original.

Wrapping a gift in two papers

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 applyingYou have
nothing yetcore
the lower line, @bb(core)
the upper line, @aa(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 timeCall time
Whenonce, as Python reads the defevery time the function is called
What runsthe decorator functions themselvesthe wrapper functions
Orderbottom to toptop wrapper starts first

Step 3: watch one call, line by line. Press Next. Before each step, say what will be printed.

Why the order flips on the way out

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)).

  1. a is nearest the function, so it wraps first: a(x).
  2. b wraps 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.

  1. First order: f = double(add1(f)).
  2. The result is $(3+1)\times2=8$.
  3. Swapped: f = add1(double(f)).
  4. 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 float

8 / 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.

  1. Original: [4, 16, 36].
  2. half (inner) divides each by 2: [2.0, 8.0, 18.0] (division always gives floats).
  3. 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 editsTravelsActs first
the argument, before calling finwardsouter (top) decorator
the result, after calling foutwardsinner (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.

  1. The call enters hi first, which adds ji: ram ji.
  2. Then upper receives it: RAM JI.
  3. The original returns Hello RAM JI.
  4. Swapped: upper acts first, giving RAM, then hi adds ji in 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

WrittenApplied (at def)Runs (on a call)
@a then @b above def ff = a(b(f))a's wrapper first, then b's, then f
@app.route("/x") then @login_requiredroute registers login_required(f)the login check runs on each request
Tips and tricks
  • 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.
Stacking rule

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.

Memory line

Wrap from the bottom. Enter from the top. Leave from the bottom.

Method for any exam question

StepDo this
1Write the one-line form, such as a(b(f)).
2Mark what each wrapper does before calling f and after it.
3Walk inwards, doing the before parts from the outside.
4Run the original once.
5Walk 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.

A volume knob for messages

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

LevelNumberFunction
DEBUG10logging.debug
INFO20logging.info
WARNING30logging.warning
ERROR40logging.error
CRITICAL50logging.critical

Step 1: compare two numbers. A message prints when its number is greater than or equal to the threshold's number.

Threshold

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

formatexample line
(default, no format)WARNING:root:done
%(levelname)s - %(message)sWARNING - done
%(levelname)s:%(message)sWARNING:done (no space)
sys.argv

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

ExpressionResultWhy
a + b23joins two strings
a * 222repeats a string
int(a) + int(b)5numbers 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.

  1. DEBUG and INFO are below WARNING: dropped.
  2. warning prints WARNING:root:w.
  3. error prints ERROR: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.

  1. a = 9, b = 3.
  2. info("checking") prints INFO - checking.
  3. 9 % 3 == 0, so the if branch calls debug, which is below INFO: nothing printed.
  4. The else branch 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

CodeOutput
logging.debug('d'); logging.info('i'); logging.warning('w')WARNING:root:w
basicConfig(level=INFO) then basicConfig(level=DEBUG), then debug and infoINFO: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.

  1. The threshold stays INFO.
  2. debug is below INFO: hidden.
  3. 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

LevelNumber
DEBUG10
INFO20
WARNING30
ERROR40
CRITICAL50

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.

  1. The warning is below ERROR, so it is dropped.
  2. print ignores logging settings.

Answer.

Only p.

Common mistake.

Hiding the print as well.

Tips and tricks
  • First find the threshold, then cross out every call below it.
  • Copy the format string literally, including spaces and colons.
  • Arguments from sys.argv are strings, and sys.argv[0] is the script name.
Memory line

Print if the message is at least the threshold. Arguments arrive as text.

Method for any exam question

StepDo this
1Find the threshold: the level given, otherwise WARNING.
2Compare each call's level with it.
3Shape each surviving line with the format.
4Check every sys.argv value for int(...) before doing arithmetic.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics