logo

... decorators: stack



Notes

To ephesize that you can stack decorators, let's apply two new ones.

import time 
import random
from functools import wraps

def print_call1(f):
    @wraps(f)
    def func(*args, **kwargs):
        print(f"print-call 1 args: {args}")
        result = f(*args, **kwargs)
        return result 
    return func


def print_call2(f):
    @wraps(f)
    def func(*args, **kwargs):
        print(f"print-call 2 args: {args}")
        result = f(*args, **kwargs)
        return result 
    return func

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

sleep_random(1.5)

Feedback? See an issue? Something unclear? Feel free to mention it here.



If you want to be kept up to date, consider signing up for the newsletter.