typestar

Writing a decorator in Python

Wrapping a function to add behavior around it.

import functools


def shout(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        result = fn(*args, **kwargs)
        return result.upper() + "!"
    return wrapper


@shout
def greet(name):
    return f"hello {name}"


loud = greet("world")

How it works

  1. shout returns a wrapper that calls the original.
  2. @functools.wraps keeps the wrapped name and docstring.
  3. @shout above greet rebinds it to the wrapper.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
229
Tokens
71
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 43 seconds.

Type this snippet

Step 2 of 5 in Decorators & closures, step 6 of 53 in Pythonic Python.

← Previous Next →