stouputils.decorators module#

This module provides decorators for various purposes:

  • silent(): Make a function silent (disable stdout, and stderr if specified) (alternative to stouputils.ctx.Muffle)

  • 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

  • simple_cache(): Easy cache function with parameter caching method

  • deprecated(): Mark a function as deprecated

stouputils decorators examples stouputils decorators examples
get_wrapper_name(decorator_name: str, func: Callable[[...], Any]) str[source]#

Get a descriptive name for a wrapper function.

Parameters:
  • decorator_name (str) – Name of the decorator

  • func (Callable[..., Any]) – Function being decorated

Returns:

Combined name for the wrapper function

Return type:

str

silent(func: Callable[[...], Any] | None = None, *, mute_stderr: bool = False) Callable[[...], Any][source]#

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

Alternative to stouputils.ctx.Muffle.

Parameters:
  • func (Callable[..., Any] | None) – Function to make silent

  • mute_stderr (bool) – Whether to mute stderr or not

Examples

>>> @silent
... def test():
...     print("Hello, world!")
>>> test()
>>> @silent(mute_stderr=True)
... def test2():
...     print("Hello, world!")
>>> test2()
>>> silent(print)("Hello, world!")
measure_time(print_func: ~collections.abc.Callable[[...], None] = <function debug>, message: str = '', perf_counter: bool = True, is_generator: bool = False) Callable[[...], Any][source]#

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

Parameters:
  • print_func (Callable) – Function to use to print the execution time (e.g. debug, info, warning, error, etc.)

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

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

  • is_generator (bool) – 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.

Return type:

Callable

Examples

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

Bases: Enum

Log level for the errors in the decorator handle_error()

NONE = 0#

Do nothing

WARNING = 1#

Show as warning

WARNING_TRACEBACK = 2#

Show as warning with traceback

ERROR_TRACEBACK = 3#

Show as error with traceback

RAISE_EXCEPTION = 4#

Raise exception

force_raise_exception: bool = False#

If true, error_log parameter will be set to RAISE_EXCEPTION for every next handle_error calls, useful for doctests

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

Decorator that handle an error with different log levels.

Parameters:
  • func (Callable[..., Any] | None) – Function to decorate

  • exceptions (tuple[type[BaseException]], ...) – Exceptions to handle

  • message (str) – Message to display with the error. (e.g. “Error during something”)

  • error_log (LogLevels) – Log level for the errors LogLevels.NONE: None LogLevels.WARNING: Show as warning LogLevels.WARNING_TRACEBACK: Show as warning with traceback LogLevels.ERROR_TRACEBACK: Show as error with traceback LogLevels.RAISE_EXCEPTION: Raise exception

  • sleep_time (float) – Time to sleep after the error (e.g. 0.0 to not sleep, 1.0 to sleep for 1 second)

Examples

>>> @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
simple_cache(func: Callable[[...], Any] | None = None, *, method: Literal['str', 'pickle'] = 'str') Callable[[...], Any][source]#

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

The str method is often faster than the pickle method (by a little).

Parameters:
  • func (Callable[..., Any] | None) – Function to cache

  • method (Literal["str", "pickle"]) – The method to use for caching.

Returns:

A decorator that caches the result of a function.

Return type:

Callable[…, Any]

Examples

>>> @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
deprecated(func: Callable[[...], Any] | None = None, *, message: str = '', error_log: LogLevels = LogLevels.WARNING) Callable[[...], Any][source]#

Decorator that marks a function as deprecated.

Parameters:
  • func (Callable[..., Any] | None) – Function to mark as deprecated

  • message (str) – Additional message to display with the deprecation warning

  • error_log (LogLevels) – Log level for the deprecation warning LogLevels.NONE: None LogLevels.WARNING: Show as warning LogLevels.WARNING_TRACEBACK: Show as warning with traceback LogLevels.ERROR_TRACEBACK: Show as error with traceback LogLevels.RAISE_EXCEPTION: Raise exception

Returns:

Decorator that marks a function as deprecated

Return type:

Callable[…, Any]

Examples

>>> @deprecated
... def old_function():
...     pass
>>> @deprecated(message="Use 'new_function()' instead", error_log=LogLevels.WARNING)
... def another_old_function():
...     pass
abstract(func: Callable[[...], Any] | None = None, *, error_log: LogLevels = LogLevels.RAISE_EXCEPTION) Callable[[...], Any][source]#

Decorator that marks a function as abstract.

Contrary to the abstractmethod decorator from the abc module 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:
  • func (Callable[..., Any] | None) – The function to mark as abstract

  • error_log (LogLevels) – Log level for the error handling LogLevels.NONE: None LogLevels.WARNING: Show as warning LogLevels.WARNING_TRACEBACK: Show as warning with traceback LogLevels.ERROR_TRACEBACK: Show as error with traceback LogLevels.RAISE_EXCEPTION: Raise exception

Returns:

Decorator that raises NotImplementedError when called

Return type:

Callable[…, Any]

Examples

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