bettermdptools.utils.decorators API documentation

# bettermdptools.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
    15    return wrapper_print_runtime
    16
    17
    18# from https://wiki.python.org/moin/PythonDecoratorLibrary
    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
    25    return decorator
    26
    27
    28# from https://realpython.com/
    29def debug(func):
    30    """Print the function signature and return value"""
    31
    32    @functools.wraps(func)
    33    def wrapper_debug(*args, **kwargs):
    34        args_repr = [repr(a) for a in args]  # 1
    35        kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]  # 2
    36        signature = ", ".join(args_repr + kwargs_repr)  # 3
    37        print(f"Calling {func.__name__}({signature})")
    38        value = func(*args, **kwargs)
    39        print(f"{func.__name__!r} returned {value!r}")  # 4
    40        return value
    41
    42    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
    16    return wrapper_print_runtime

def add_to(func): View Source

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

def debug(func): View Source

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

Print the function signature and return value