Calmcode - decorators: inputs

Inputs

1 2 3 4 5 6 7 8 9 10

We can also have decorators that accept inputs. This makes for even more expressiveness. You do need to pay attention when you're declaring them though.

The example below gives a full demonstration.

import time
import random
from functools import wraps

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

@loggg(show_name=False, show_time=True)
def sleep_random(s):
    """This function sleeps at least for `s` seconds."""
    return time.sleep(s + random.random()/100)

sleep_random(1)