Conditions | 10 |
Total Lines | 52 |
Lines | 0 |
Ratio | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
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 |
||
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 | |||
85 |