carlogtt_python_library.utils.decorators module
This module contains useful decorators that can be used in the application.
- class carlogtt_python_library.utils.decorators.BenchmarkResolution(*values)[source]
Bases:
EnumDefines time resolution units and their corresponding duration in seconds.
- DAYS = ('days', 86400)
- HOURS = ('hours', 3600)
- MINUTES = ('minutes', 60)
- SECONDS = ('seconds', 1)
- carlogtt_python_library.utils.decorators.benchmark_execution(logger: Logger = <Logger carlogtt_python_library.utils.decorators (WARNING)>, resolution: str | BenchmarkResolution = BenchmarkResolution.SECONDS) Callable[[Callable[[P], R]], Callable[[P], R]][source]
Measure and log the execution time of the decorated function.
- Parameters:
logger – The logging.Logger instance to be used for logging the execution time of the decorated function. If not explicitly provided, the function uses Python’s standard logging module as a default logger.
resolution – The time unit for reporting execution time. Can be either: - A string from {“sec”, “min”, “hour”, “day”}, or - An instance of BenchmarkResolution (e.g. BenchmarkResolution.SECONDS). Defaults to BenchmarkResolution.SECONDS.
- carlogtt_python_library.utils.decorators.log_execution(logger: Logger = <Logger carlogtt_python_library.utils.decorators (WARNING)>) Callable[[Callable[[P], R]], Callable[[P], R]][source]
Log the start and completion of the decorated function using the provided logger.
- Parameters:
logger – The logging.Logger instance to be used for logging the execution time of the decorated function. If not explicitly provided, the function uses Python’s standard logging module as a default logger.
- class carlogtt_python_library.utils.decorators.retry(exception_to_check: type[Exception] | ~collections.abc.Iterable[type[Exception]], tries: int = 4, delay_secs: int = 3, delay_multiplier: int = 2, logger: ~logging.Logger = <Logger carlogtt_python_library.utils.decorators (WARNING)>)[source]
Bases:
objectRetry helper that works both as a decorator and as a context manager, using an exponential backoff multiplier.
Examples
Decorator usage:
@retry((TimeoutError, ConnectionError), tries=5, delay_secs=1) def fetch(url: str) -> bytes: ...
Context-manager usage:
with retry(ValueError, tries=3) as retryer: data = retryer(load_csv, "data.csv") retryer(save_report, path="out.pdf", data=data)
- Parameters:
exception_to_check – the exception to check. may be a tuple of exceptions to check
tries – number of times to try (not retry) before giving up
delay_secs – initial delay between retries in seconds
delay_multiplier – delay multiplier e.g. value of 2 will double the delay each retry
logger – The logging.Logger instance to be used for logging the execution time of the decorated function. If not explicitly provided, the function uses Python’s standard logging module as a default logger.