Bitpath

Lesson 2 · Unit 02

Decorators

Functions that take a function and return a replacement

13 exercisesabout 3 min

What you practise

  • A function that takes and returns a function, @ as plain assignment, functools.wraps, decorators with arguments, lru_cache

Try a question from this lesson

Pick one

The second-to-last line replaces a function with whatever another function returns. What prints?

Python
def loud(func):
    def wrapper(name):
        return func(name).upper()
    return wrapper

def greet(name):
    return "hi " + name

greet = loud(greet)
print(greet("ada"))
Hint

After the reassignment, the name refers to the inner function. What does that one do?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

@ is an assignment

Writing @loud above a def is exactly greet = loud(greet) after it.

So a decorator is any callable that takes a function and returns what the name should now refer to: usually a wrapper that adds something and calls the original.

Python
def loud(func):
    def wrapper(name):
        return func(name).upper()
    return wrapper

@loud
def greet(name):
    return "hi " + name

print(greet("ada"))   # HI ADA

Concept

Stacking, and any arguments

A wrapper that takes *args, **kwargs and passes them on works for a function of any signature.

Several decorators apply from the bottom up: the one nearest the def wraps first, and the top one ends up outermost.

@first
@second
def f():
    ...

# is the same as:
f = first(second(f))

10 more exercises in the app

  • 4× type the answer
  • 2× multiple choice
  • 2× fill the blanks
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy