Skip to content

Decorators

Decorators for adding functionality to functions and methods.


deprecated

deprecated(msg, klass=PendingDeprecationWarning)

Decorator to mark a function as deprecated.

Emits a deprecation warning when the decorated function is called.

Parameters:

Name Type Description Default
msg

Warning message to display.

required
klass

Warning class to use. Defaults to PendingDeprecationWarning.

PendingDeprecationWarning
Source code in src/aibs_informatics_core/utils/decorators.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def deprecated(msg, klass=PendingDeprecationWarning):
    """Decorator to mark a function as deprecated.

    Emits a deprecation warning when the decorated function is called.

    Args:
        msg: Warning message to display.
        klass: Warning class to use. Defaults to ``PendingDeprecationWarning``.
    """

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            warnings.warn(msg, klass, stacklevel=2)
            return func(*args, **kwargs)

        return wrapper

    return decorator

retry

retry(
    retryable_exceptions,
    retryable_exception_callbacks=None,
    tries=4,
    delay=3,
    backoff=2,
    logger=None,
)

Retry calling the decorated function using an exponential backoff.

http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry

Parameters:

Name Type Description Default
retryable_exceptions (Exception, tuple)

One or more exception classes to retry on. May be a single exception class or tuple of exceptions classes to check.

required
retryable_exception_callbacks (Optional, [Callable[[Exception], bool]])

Optional callback function to inspect retryable exceptions. If returns False, the exception is raised.

None
tries int

number of times to try (not retry) before giving up

4
delay (int, float)

initial delay between retries in seconds

3
backoff int

backoff multiplier e.g. value of 2 will double the delay each retry

2
logger Logger

logger to use. The default logger runs in the decorators namespace, but this can be overridden by passing one in.

None

Returns:

Type Description

decorated function

Source code in src/aibs_informatics_core/utils/decorators.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def retry(
    retryable_exceptions: ExceptionTypes,
    retryable_exception_callbacks: None
    | (list[ExceptionCallbackType | tuple[type[Exception], ExceptionCallbackType]]) = None,
    tries: int = 4,
    delay: float = 3,
    backoff: float = 2,
    logger: logging.Logger | None = None,
):
    """Retry calling the decorated function using an exponential backoff.

    http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
    original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry


    Args:
        retryable_exceptions (Exception, tuple): One or more exception classes to retry on. May
            be a single exception class or tuple of exceptions classes to check.
        retryable_exception_callbacks (Optional,[Callable[[Exception], bool]]): Optional callback
            function to inspect retryable exceptions. If returns False, the exception is raised.
        tries (int): number of times to try (not retry) before giving up
        delay (int, float): initial delay between retries in seconds
        backoff (int): backoff multiplier e.g. value of 2 will double the delay each retry
        logger (logging.Logger): logger to use. The default logger runs in the decorators
                                 namespace, but this can be overridden by passing one in.

    Returns:
        decorated function
    """
    logger = logger or logging.getLogger(__name__)

    def deco_retry(f):
        @wraps(f)
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except retryable_exceptions as ex:
                    applicable_callbacks = [
                        callback
                        for type_ex, callback in [
                            (None, _) if not isinstance(_, tuple) else _
                            for _ in retryable_exception_callbacks or []
                        ]
                        if not type_ex or issubclass(type(ex), type_ex)
                    ]

                    # Raise exception if
                    # 1. There are applicable callbacks
                    # 2. no callbacks return true
                    if applicable_callbacks and not any(
                        [callback(ex) for callback in applicable_callbacks]
                    ):
                        raise ex
                    assert logger is not None
                    logger.warning("%s, Retrying in %d seconds..." % (str(ex), mdelay))
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return f(*args, **kwargs)

        return f_retry  # true decorator

    return deco_retry