utils.decorators API documentation

# utils.decorators

View Source

     1import functools
     2import time
     3
     4
     5def print_runtime(func):
     6    @functools.wraps(func)
     7    def wrapper_print_runtime(*args, **kwargs):
     8        start = time.time()
     9        value = func(*args, **kwargs)
    10        end = time.time()
    11        running_time = end - start
    12        print("runtime = %.2f seconds" % running_time)
    13        return value
    14    return wrapper_print_runtime
    15
    16
    17# from https://wiki.python.org/moin/PythonDecoratorLibrary
    18def add_to(func):
    19    @functools.wraps(func)
    20    def decorator(*args, **kwargs):
    21        setattr(func, args[0].__name__, args[0])
    22        return func
    23    return decorator
    24
    25
    26# from https://realpython.com/
    27def debug(func):
    28    """Print the function signature and return value"""
    29    @functools.wraps(func)
    30    def wrapper_debug(*args, **kwargs):
    31        args_repr = [repr(a) for a in args]                      # 1
    32        kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]  # 2
    33        signature = ", ".join(args_repr + kwargs_repr)           # 3
    34        print(f"Calling {func.__name__}({signature})")
    35        value = func(*args, **kwargs)
    36        print(f"{func.__name__!r} returned {value!r}")           # 4
    37        return value
    38    return wrapper_debug

def print_runtime(func): View Source

     6def print_runtime(func):
     7    @functools.wraps(func)
     8    def wrapper_print_runtime(*args, **kwargs):
     9        start = time.time()
    10        value = func(*args, **kwargs)
    11        end = time.time()
    12        running_time = end - start
    13        print("runtime = %.2f seconds" % running_time)
    14        return value
    15    return wrapper_print_runtime

def add_to(func): View Source

    19def add_to(func):
    20    @functools.wraps(func)
    21    def decorator(*args, **kwargs):
    22        setattr(func, args[0].__name__, args[0])
    23        return func
    24    return decorator

def debug(func): View Source

    28def debug(func):
    29    """Print the function signature and return value"""
    30    @functools.wraps(func)
    31    def wrapper_debug(*args, **kwargs):
    32        args_repr = [repr(a) for a in args]                      # 1
    33        kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]  # 2
    34        signature = ", ".join(args_repr + kwargs_repr)           # 3
    35        print(f"Calling {func.__name__}({signature})")
    36        value = func(*args, **kwargs)
    37        print(f"{func.__name__!r} returned {value!r}")           # 4
    38        return value
    39    return wrapper_debug

Print the function signature and return value