decorators logo decorators: wraps

1 2 3 4 5 6 7 8 9 10

When we wrap a function with a decorator we might loose information from the original function. One of the things we miss out on is the docstring.

Let's make sure that the docstring is kept intact by using @wraps.

import time
import random

def stopwatch(f):
    def func(*args, **kwargs):
        tic = time.time()
        result = f(*args, **kwargs)
        print(f"this function took: {time.time() - tic}")
        return result
    return func

def sleep_random(s):
    """This function sleeps at least for `s` seconds."""
    return time.sleep(s + random.random())

timed_sleep = stopwatch(sleep_random)

Note that we now no longer have two functions, but one!