×

python · level 3 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.