stouputils.decorators package#

This module provides decorators for various purposes:

  • @measure_time - Measure the execution time of a function and print it with the given print function

  • @handle_error - Handle an error with different log levels

  • @timeout - Raise an exception if the function runs longer than the specified timeout

  • @retry - Retry a function when specific exceptions are raised, with configurable delay and max attempts

  • @simple_cache - Easy cache function with parameter caching method

  • @abstract - Mark a function as abstract, using LogLevels for error handling

  • @deprecated - Mark a function as deprecated, using LogLevels for warning handling

  • @silent - Make a function silent, on stdout and optionally stderr (alternative to stouputils.ctx.Muffle)

import time
import stouputils as stp

# Print how long each call takes, and remember results so a repeated call is instant
@stp.measure_time
@stp.simple_cache
def slow_square(x: int) -> int:
        time.sleep(0.5)
        return x * x

slow_square(12)
slow_square(12)

# On a ConnectionError, call again up to 5 times, waiting 0.3 seconds in between
attempts = 0

@stp.retry(exceptions=ConnectionError, max_attempts=5, delay=0.3)
def fetch() -> str:
        global attempts
        attempts += 1
        if attempts < 3:
                raise ConnectionError("Busy")
        return "<html>"

stp.info("Fetched", fetch())

# Turn an error into a warning instead of stopping the program
@stp.handle_error(error_log=stp.LogLevels.WARNING)
def read_port(text: str) -> int:
        return int(text)

read_port("abc")

# Warn whoever still calls an old function
@stp.deprecated(message="Use fetch() instead")
def download() -> str:
        return fetch()

download()
Terminal output of the example, with timings, retries and warnings

Submodules#