retry()   D
last analyzed

Complexity

Conditions 10

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
dl 0
loc 52
rs 4.5
c 3
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C retry_aspect() 0 20 8

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like retry() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import time
2
from logging import getLogger
3
4
from aspectlib import Aspect
5
6
logger = getLogger(__name__)
7
8
9
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep):
10
    """
11
    Decorator that retries the call ``retries`` times if ``func`` raises ``exceptions``. Can use a ``backoff`` function
12
    to sleep till next retry.
13
14
    Example::
15
16
        >>> should_fail = lambda foo=[1,2,3]: foo and foo.pop()
17
        >>> @retry
18
        ... def flaky_func():
19
        ...     if should_fail():
20
        ...         raise OSError('Tough luck!')
21
        ...     print("Success!")
22
        ...
23
        >>> flaky_func()
24
        Success!
25
26
    If it reaches the retry limit::
27
28
        >>> @retry
29
        ... def bad_func():
30
        ...     raise OSError('Tough luck!')
31
        ...
32
        >>> bad_func()
33
        Traceback (most recent call last):
34
        ...
35
        OSError: Tough luck!
36
37
    """
38
39
    @Aspect(bind=True)
40
    def retry_aspect(cutpoint, *args, **kwargs):
41
        for count in range(retries + 1):
42
            try:
43
                if count and cleanup:
44
                    cleanup(*args, **kwargs)
45
                yield
46
                break
47
            except exceptions as exc:
48
                if count == retries:
49
                    raise
50
                if not backoff:
51
                    timeout = 0
52
                elif isinstance(backoff, (int, float)):
53
                    timeout = backoff
54
                else:
55
                    timeout = backoff(count)
56
                logger.exception("%s(%s, %s) raised exception %s. %s retries left. Sleeping %s secs.",
57
                                 cutpoint.__name__, args, kwargs, exc, retries - count, timeout)
58
                sleep(timeout)
59
60
    return retry_aspect if func is None else retry_aspect(func)
61
62
63
def exponential_backoff(count):
64
    """
65
    Wait 2**N seconds.
66
    """
67
    return 2 ** count
68
retry.exponential_backoff = exponential_backoff
69
70
71
def straight_backoff(count):
72
    """
73
    Wait 1, 2, 5 seconds. All retries after the 3rd retry will wait 5*N-5 seconds.
74
    """
75
    return (1, 2, 5)[count] if count < 3 else 5 * count - 5
76
retry.straight_backoff = straight_backoff
77
78
79
def flat_backoff(count):
80
    """
81
    Wait 1, 2, 5, 10, 15, 30 and 60 seconds. All retries after the 5th retry will wait 60 seconds.
82
    """
83
    return (1, 2, 5, 10, 15, 30, 60)[count if count < 6 else -1]
84
retry.flat_backoff = flat_backoff
85