🎯 decorators#

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 (like 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

abstraction#

abstract(
func: Callable[[...], T] | None = None,
*,
error_log: LogLevels = LogLevels.RAISE_EXCEPTION,
) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that marks a function as abstract.

Contrary to the abc.abstractmethod() decorator that raises a TypeError when you try to instantiate a class that has abstract methods, this decorator raises a NotImplementedError ONLY when the decorated function is called, indicating that the function must be implemented by a subclass.

Parameters:
>>> class Base:
...     @abstract
...     def method(self):
...         pass
>>> Base().method()
Traceback (most recent call last):
    ...
NotImplementedError: Function 'method()' is abstract and must be implemented by a subclass

caching#

CACHE_CLEARERS: list[Callable[[], None]] = [<built-in method cache_clear of functools._lru_cache_wrapper object>][source]#

The function emptying each cache simple_cache() created, which clear_simple_caches() calls in turn.

clear_simple_caches() → None[source]#

Clear every cache created by simple_cache().

Useful for long-lived processes that run the same code on changing state: call this at the start of each cycle so cached results (and skipped side effects) from a previous cycle can’t leak into the next one.

>>> @simple_cache
... def count_calls(x: int, _calls: list[int] = []) -> int:
...     _calls.append(x)
...     return len(_calls)
>>> count_calls(1), count_calls(1)
(1, 1)
>>> clear_simple_caches()
>>> count_calls(1)
2
simple_cache(
func: Callable[[...], T] | None = None,
*,
method: Literal['hash', 'str', 'pickle'] | Callable[[tuple[Any, ...], dict[str, Any]], Any] = 'hash',
) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that caches the result of a function based on its arguments.

The default hash method is the fastest, being functools.cache() and its C implementation, at the cost of two restrictions. It requires every argument to be hashable, and equal arguments of different types such as 1.0 and True may share an entry. Switch to the str method for unhashable arguments, and to the pickle method for complex objects needing an exact key. The caching method is resolved once at decoration time, so an invalid one raises immediately instead of on first call.

Parameters:
  • func – Function to cache

  • method – The method to use for caching, or a callable building the key.

>>> @simple_cache
... def test1(a: int, b: int) -> int:
...     return a + b
>>> @simple_cache(method="str")
... def test2(a: int, b: int) -> int:
...     return a + b
>>> test2(1, 2)
3
>>> test2(1, 2)
3
>>> test2(3, 4)
7

Cache a recursive function:

>>> @simple_cache
... def factorial(n: int) -> int:
...     return n * factorial(n - 1) if n else 1
>>> factorial(10)   # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)    # no new calls, just returns the cached result
120
>>> factorial(12)   # two new recursive calls, factorial(10) is cached
479001600

The default hash method uses the arguments themselves as key, so the str method is needed for unhashable ones:

>>> @simple_cache
... def test4(a: list[int], b: int) -> int:
...     return sum(a) + b
>>> test4([1], 2)
Traceback (most recent call last):
TypeError: ...unhashable type: 'list'...
>>> @simple_cache(method="str")
... def test5(a: list[int], b: int) -> int:
...     return sum(a) + b
>>> test5([1], 2)
3

Prevent a function from running more than once regardless of arguments:

>>> @simple_cache(method=lambda x, y: 1)
... def execute_one_time() -> None:
...     print("Executed!")
>>> _ = [execute_one_time() for _ in range(3)]
Executed!

An unknown method is rejected right away:

>>> @simple_cache(method="json")
... def test3() -> None: ...
Traceback (most recent call last):
ValueError: Invalid caching method 'json'...

common#

WRAPPED_ATTRIBUTE: str = '__wrapped__'[source]#

Attribute functools assigns last, so that inspect.signature() follows a wrapper back to the original.

safe_wraps(
wrapped: Any,
) → Callable[[WrapperT], WrapperT][source]#

Tolerant replacement for functools.wraps(), copying only the metadata that can actually be copied.

functools.wraps assigns __type_params__ among other attributes, and a function object rejects any value that is not a tuple. Decorating an object whose attributes are synthesised, such as a Sphinx autodoc mock, therefore raises TypeError and takes down the import of every module that touches the decorated symbol. Skipping the attributes that refuse to be copied keeps the decorator working on anything callable.

Parameters:

wrapped – Object the wrapper stands for

Returns:

Decorator applying the metadata to a wrapper

>>> def original(a: int) -> int:
...     ''' Doc. '''
...     return a
>>> @safe_wraps(original)
... def wrapper(*args: Any, **kwargs: Any) -> int: ...
>>> wrapper.__name__, wrapper.__doc__.strip()
('original', 'Doc.')

An attribute a function refuses is skipped, where functools.wraps would raise TypeError:

>>> class Synthetic:
...     __type_params__ = "not a tuple"
>>> @safe_wraps(Synthetic())
... def survivor() -> None: ...
>>> survivor.__name__
'survivor'
get_function_name(
func: CallableAny,
) → str[source]#

Get the name of a function, returns “<unknown>” if the name cannot be retrieved.

get_wrapper_name(
decorator_name: str,
func: CallableAny,
) → str[source]#

Get a descriptive name for a wrapper function.

Parameters:
  • decorator_name – Name of the decorator

  • func – Function being decorated

Returns:

Combined name for the wrapper function (e.g., “stouputils.decorators.handle_error@function_name”)

set_wrapper_name(
wrapper: CallableAny,
name: str,
) → None[source]#

Set the wrapper function’s visible name (code object name) for clearer tracebacks.

Parameters:
  • wrapper – Wrapper function to update

  • name – New name to set

deprecation#

deprecated(
func: Callable[[...], T] | None = None,
*,
message: str = '',
version: str = '',
error_log: LogLevels = LogLevels.WARNING,
) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that marks a function as deprecated.

Parameters:
>>> @deprecated
... def old_function():
...     pass
>>> @deprecated(message="Use 'new_function()' instead", error_log=LogLevels.WARNING)
... def another_old_function():
...     pass

error_handling#

class LogLevels(*values)[source]#

Bases: Enum

Log level for the errors in the decorator handle_error

NONE = 0[source]#

Do nothing

WARNING = 1[source]#

Show as warning

WARNING_TRACEBACK = 2[source]#

Show as warning with traceback

ERROR_TRACEBACK = 3[source]#

Show as error with traceback

RAISE_EXCEPTION = 4[source]#

Raise exception

handle_error(func: ~collections.abc.Callable[[...], T] | None = None, *, exceptions: tuple[type[BaseException], ...] | type[BaseException] = (<class 'Exception'>,), message: str = '', error_log: ~stouputils.decorators.error_handling.LogLevels = LogLevels.WARNING_TRACEBACK, sleep_time: float = 0.0, callback: ~collections.abc.Callable[[BaseException], None] | None = None) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that handle an error with different log levels.

Parameters:
>>> @handle_error
... def might_fail():
...     raise ValueError("Let's fail")
>>> @handle_error(error_log=LogLevels.WARNING)
... def test():
...     raise ValueError("Let's fail")
>>> # test()    # [WARNING HH:MM:SS] Error during test: (ValueError) Let's fail
report_error(
error_log: LogLevels,
heading: str,
exception: BaseException,
sleep_time: float,
callback: Callable[[BaseException], None] | None,
) → None[source]#

React to an exception handle_error() caught at a level that does not raise, from inside its except block.

Parameters:
  • heading – Opening of the message, naming where the exception happened.

  • sleep_time – Seconds to sleep afterwards, skipped at ERROR_TRACEBACK since its prompt already waited.

retrying#

class RetryPolicy(
exceptions: tuple[type[BaseException], ...],
attempt_limit: int | None,
delays: tuple[float, ...] | None,
delay: float,
backoff: float,
message: str,
on_each_failure: Callable[[BaseException, int], Any] | None,
)[source]#

Bases: object

Helper class for how retry() calls a function again: on which exceptions, how many times, and after which waits.

exceptions: tuple[type[BaseException], ...][source]#

Exceptions to catch and retry on.

attempt_limit: int | None[source]#

Attempts allowed in total, None for no limit.

delays: tuple[float, ...] | None[source]#

Seconds to wait after each failed attempt, replacing delay and backoff when given.

delay: float[source]#

Initial delay in seconds between retries (default: 1.0).

backoff: float[source]#

Multiplier for delay after each retry (default: 1.0 for constant delay).

message: str[source]#

Custom message to display before “, retrying” (default: “{ExceptionName} encountered while running {func_name}”).

on_each_failure: Callable[[BaseException, int], Any] | None[source]#

Optional callback function to call on each failure, receives the exception and the attempt number as arguments.

call(
func: Callable[[...], T],
args: tuple[Any, ...],
kwargs: dict[str, Any],
) → T[source]#

Call func until it returns, raising its last exception once the attempts run out.

wait_after(attempt: int) → float[source]#

Seconds to wait after the given failed attempt, counted from 1.

retry(func: ~collections.abc.Callable[[...], T] | None = None, *, exceptions: tuple[type[BaseException], ...] | type[BaseException] = (<class 'Exception'>,), max_attempts: int | ~collections.abc.Iterable[float] | None = 10, delay: float = 1.0, backoff: float = 1.0, message: str = '', on_each_failure: ~collections.abc.Callable[[BaseException, int], ~typing.Any] | None = None) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that retries a function when specific exceptions are raised.

Parameters:
  • func – Function to retry

  • exceptions – Exceptions to catch and retry on

  • max_attempts – Maximum number of attempts, None for infinite retries. An iterable of seconds gives one delay per attempt instead: its length is the attempt count, and delay/backoff are ignored.

  • delay – Initial delay in seconds between retries (default: 1.0)

  • backoff – Multiplier for delay after each retry (default: 1.0 for constant delay)

  • message – Custom message to display before “, retrying” (default: “{ExceptionName} encountered while running {func_name}”)

  • on_each_failure – Optional callback function to call on each failure, receives the exception and the attempt number as arguments

Returns:

Decorator that retries the function on specified exceptions

>>> import os
>>> @retry(exceptions=PermissionError, max_attempts=3, delay=0.1)
... def write_file():
...     with open("test.txt", "w") as f:
...         f.write("test")
>>> @retry(exceptions=(OSError, IOError), delay=0.5, backoff=2.0)
... def network_call():
...     pass
>>> @retry(max_attempts=5, delay=1.0)
... def might_fail():
...     pass
>>> # Use a lambda to record attempts on each failure
>>> calls = []
>>> @retry(max_attempts=3, delay=0.0, on_each_failure=lambda e, a: calls.append((e, a)))
... def will_fail():
...     raise RuntimeError("nope")
>>> try:
...     will_fail()
... except RuntimeError:
...     pass
>>> calls
[(RuntimeError('nope'), 1), (RuntimeError('nope'), 2), (RuntimeError('nope'), 3)]
>>> # An iterable of delays sets both the waits and the attempt count
>>> attempts = []
>>> @retry(max_attempts=(0.0, 0.0, 0.0, 0.0), on_each_failure=lambda e, a: attempts.append(a))
... def flaky():
...     raise ValueError("nope")
>>> try:
...     flaky()
... except ValueError:
...     pass
>>> attempts
[1, 2, 3, 4]
retry_warning(
error: BaseException,
func: Callable[[...], Any],
message: str,
delay: float,
attempt: int,
attempt_limit: int | None,
) → str[source]#

The warning retry() prints before waiting for the next attempt.

Parameters:
  • message – Text opening the warning, the error and the function name when empty.

  • attempt – Number of the attempt that just failed, from 1.

  • attempt_limit – Attempts allowed in total, None for no limit.

>>> retry_warning(OSError("busy"), print, "", 0.5, 1, None)
'OSError encountered while running print(), retrying in 0.5s (2/∞): busy'
>>> retry_warning(OSError("busy"), print, "Lock taken", 2.0, 2, 3)
'Lock taken, retrying in 2.0s (3/3): busy'

silencing#

silent(
func: Callable[[...], T] | None = None,
*,
mute_stderr: bool = False,
replay_on_error: bool = False,
error_log_level: int | None = None,
watch_loggers: Sequence[str] | None = None,
) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that makes a function silent (disable stdout, and stderr if specified).

Alternative to Muffle.

Parameters:
  • func – Function to make silent

  • mute_stderr – Whether to mute stderr or not

  • replay_on_error – Capture output and replay it if the call errors (see Muffle)

  • error_log_level – Also treat log records at/above this level as an error (e.g. logging.ERROR)

  • watch_loggers – Names of the loggers to watch for error_log_level (default: root logger only)

>>> @silent
... def test():
...     print("Hello, world!")
>>> test()
>>> @silent(mute_stderr=True)
... def test2():
...     print("Hello, world!")
>>> test2()
>>> silent(print)("Hello, world!")
>>> # Only shows the output if the wrapped call fails
>>> @silent(replay_on_error=True)
... def test3():
...     print("Context that explains the failure below")
...     raise ValueError("boom")
>>> try:
...     test3()
... except ValueError:
...     pass
Context that explains the failure below

timeouts#

timeout(
func: Callable[[...], T] | None = None,
*,
seconds: float = 60.0,
message: str = '',
) → Callable[[...], T] | Callable[[Callable[[...], T]], Callable[[...], T]][source]#

Decorator that raises a TimeoutError if the function runs longer than the specified timeout.

Note: This decorator uses SIGALRM on Unix systems, which only works in the main thread. On Windows or in non-main threads, it will fall back to a polling-based approach.

Parameters:
  • func – Function to apply timeout to

  • seconds – Timeout duration in seconds (default: 60.0)

  • message – Custom timeout message (default: “Function ‘{func_name}’ timed out after {seconds} seconds”)

Raises:

TimeoutError – If the function execution exceeds the timeout duration

>>> import time
>>> @timeout(seconds=2.0)
... def slow_function():
...     time.sleep(5)
>>> slow_function()  # Raises TimeoutError after 2 seconds
Traceback (most recent call last):
    ...
TimeoutError: Function 'slow_function()' timed out after 2.0 seconds
>>> @timeout(seconds=1.0, message="Custom timeout message")
... def another_slow_function():
...     time.sleep(3)
>>> another_slow_function()  # Raises TimeoutError after 1 second
Traceback (most recent call last):
    ...
TimeoutError: Custom timeout message
run_with_alarm(
func: Callable[[...], T],
args: tuple[Any, ...],
kwargs: dict[str, Any],
seconds: float,
message: str,
) → T[source]#

Call func under a SIGALRM timer, which interrupts it wherever it is, restoring the previous handler afterwards.

Raises:
  • TimeoutError – If the call outlasts seconds, carrying message.

  • NotImplementedError – On Windows, which has no SIGALRM.

run_in_thread(
func: Callable[[...], T],
args: tuple[Any, ...],
kwargs: dict[str, Any],
seconds: float,
message: str,
) → T[source]#

Call func in a daemon thread and stop waiting after seconds, the thread itself running on until it returns.

Raises:

TimeoutError – If the call outlasts seconds, carrying message.

timing#

measure_time(func: ~collections.abc.Callable[[...], T] | ~collections.abc.Callable[[...], ~collections.abc.Generator[T, None, None]] | None = None, *, printer: ~collections.abc.Callable[[...], None] = <function progress>, message: str = '', perf_counter: bool = True, is_generator: bool = False) → Callable[[...], T] | Callable[[...], Generator[T, None, None]] | Callable[[Callable[[...], T]], Callable[[...], T]] | Callable[[Callable[[...], Generator[T, None, None]]], Callable[[...], Generator[T, None, None]]][source]#

Decorator that will measure the execution time of a function and print it with the given print function

Parameters:
  • func – Function to decorate

  • printer – Function to use to print the execution time (e.g. debug(), info() or warning())

  • message – Message to display with the execution time (e.g. “Execution time of Something”), defaults to “Execution time of {func.__name__}”

  • perf_counter – Whether to use time.perf_counter_ns or time.time_ns defaults to True (use time.perf_counter_ns)

  • is_generator – Whether the function is a generator or not (default: False) When True, the decorator will yield from the function instead of returning it.

Returns:

Decorator to measure the time of the function.

> @measure_time(printer=info)
> def test():
>     pass
> test()  # [INFO HH:MM:SS] Execution time of test: 0.000ms (400ns)