decorators logo decorators: optional inputs

1 2 3 4 5 6 7 8 9 10

To make inputs optional, we need to do something nitty-gritty. We need to make sure that if no inputs are given, the decorated function is still able to run. The code below shows you how you might get that to work.

import time
import random
from functools import wraps

def loggg(func_in=None, *, show_name=True, show_time=True):
    def stopwatch(f):
        def func(*args, **kwargs):
            tic = time.time()
            result = f(*args, **kwargs)
            result = "call"
            if show_name:
                result = f"{result} {f.__name__}"
            if show_time:
                result = f"{result} time:{time.time() - tic}"
            return result
        return func

    # This is where the "magic" happens.
    if func_in is None:
        return stopwatch
        return stopwatch(func_in)

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


Feel free to review this topic again over a period of time. It's very normal if the entire abstraction doesn't 100% "click" right away.