... decorators: optional inputs


To make inputs optional, we need to do something nitty-gritty.

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.

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.