README.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. Tenacity
  2. ========
  3. .. image:: https://img.shields.io/pypi/v/tenacity.svg
  4. :target: https://pypi.python.org/pypi/tenacity
  5. .. image:: https://circleci.com/gh/jd/tenacity.svg?style=svg
  6. :target: https://circleci.com/gh/jd/tenacity
  7. .. image:: https://img.shields.io/endpoint.svg?url=https://dashboard.mergify.io/badges/jd/tenacity&style=flat
  8. :target: https://mergify.io
  9. :alt: Mergify Status
  10. Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in
  11. Python, to simplify the task of adding retry behavior to just about anything.
  12. It originates from `a fork of retrying
  13. <https://github.com/rholder/retrying/issues/65>`_ which is sadly no longer
  14. `maintained <https://julien.danjou.info/python-tenacity/>`_. Tenacity isn't
  15. api compatible with retrying but adds significant new functionality and
  16. fixes a number of longstanding bugs.
  17. The simplest use case is retrying a flaky function whenever an `Exception`
  18. occurs until a value is returned.
  19. .. testcode::
  20. import random
  21. from tenacity import retry
  22. @retry
  23. def do_something_unreliable():
  24. if random.randint(0, 10) > 1:
  25. raise IOError("Broken sauce, everything is hosed!!!111one")
  26. else:
  27. return "Awesome sauce!"
  28. print(do_something_unreliable())
  29. .. testoutput::
  30. :hide:
  31. Awesome sauce!
  32. .. toctree::
  33. :hidden:
  34. :maxdepth: 2
  35. changelog
  36. api
  37. Features
  38. --------
  39. - Generic Decorator API
  40. - Specify stop condition (i.e. limit by number of attempts)
  41. - Specify wait condition (i.e. exponential backoff sleeping between attempts)
  42. - Customize retrying on Exceptions
  43. - Customize retrying on expected returned result
  44. - Retry on coroutines
  45. - Retry code block with context manager
  46. Installation
  47. ------------
  48. To install *tenacity*, simply:
  49. .. code-block:: bash
  50. $ pip install tenacity
  51. Examples
  52. ----------
  53. Basic Retry
  54. ~~~~~~~~~~~
  55. .. testsetup:: *
  56. import logging
  57. #
  58. # Note the following import is used for demonstration convenience only.
  59. # Production code should always explicitly import the names it needs.
  60. #
  61. from tenacity import *
  62. class MyException(Exception):
  63. pass
  64. As you saw above, the default behavior is to retry forever without waiting when
  65. an exception is raised.
  66. .. testcode::
  67. @retry
  68. def never_give_up_never_surrender():
  69. print("Retry forever ignoring Exceptions, don't wait between retries")
  70. raise Exception
  71. Stopping
  72. ~~~~~~~~
  73. Let's be a little less persistent and set some boundaries, such as the number
  74. of attempts before giving up.
  75. .. testcode::
  76. @retry(stop=stop_after_attempt(7))
  77. def stop_after_7_attempts():
  78. print("Stopping after 7 attempts")
  79. raise Exception
  80. We don't have all day, so let's set a boundary for how long we should be
  81. retrying stuff.
  82. .. testcode::
  83. @retry(stop=stop_after_delay(10))
  84. def stop_after_10_s():
  85. print("Stopping after 10 seconds")
  86. raise Exception
  87. You can combine several stop conditions by using the `|` operator:
  88. .. testcode::
  89. @retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
  90. def stop_after_10_s_or_5_retries():
  91. print("Stopping after 10 seconds or 5 retries")
  92. raise Exception
  93. Waiting before retrying
  94. ~~~~~~~~~~~~~~~~~~~~~~~
  95. Most things don't like to be polled as fast as possible, so let's just wait 2
  96. seconds between retries.
  97. .. testcode::
  98. @retry(wait=wait_fixed(2))
  99. def wait_2_s():
  100. print("Wait 2 second between retries")
  101. raise Exception
  102. Some things perform best with a bit of randomness injected.
  103. .. testcode::
  104. @retry(wait=wait_random(min=1, max=2))
  105. def wait_random_1_to_2_s():
  106. print("Randomly wait 1 to 2 seconds between retries")
  107. raise Exception
  108. Then again, it's hard to beat exponential backoff when retrying distributed
  109. services and other remote endpoints.
  110. .. testcode::
  111. @retry(wait=wait_exponential(multiplier=1, min=4, max=10))
  112. def wait_exponential_1():
  113. print("Wait 2^x * 1 second between each retry starting with 4 seconds, then up to 10 seconds, then 10 seconds afterwards")
  114. raise Exception
  115. Then again, it's also hard to beat combining fixed waits and jitter (to
  116. help avoid thundering herds) when retrying distributed services and other
  117. remote endpoints.
  118. .. testcode::
  119. @retry(wait=wait_fixed(3) + wait_random(0, 2))
  120. def wait_fixed_jitter():
  121. print("Wait at least 3 seconds, and add up to 2 seconds of random delay")
  122. raise Exception
  123. When multiple processes are in contention for a shared resource, exponentially
  124. increasing jitter helps minimise collisions.
  125. .. testcode::
  126. @retry(wait=wait_random_exponential(multiplier=1, max=60))
  127. def wait_exponential_jitter():
  128. print("Randomly wait up to 2^x * 1 seconds between each retry until the range reaches 60 seconds, then randomly up to 60 seconds afterwards")
  129. raise Exception
  130. Sometimes it's necessary to build a chain of backoffs.
  131. .. testcode::
  132. @retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +
  133. [wait_fixed(7) for i in range(2)] +
  134. [wait_fixed(9)]))
  135. def wait_fixed_chained():
  136. print("Wait 3s for 3 attempts, 7s for the next 2 attempts and 9s for all attempts thereafter")
  137. raise Exception
  138. Whether to retry
  139. ~~~~~~~~~~~~~~~~
  140. We have a few options for dealing with retries that raise specific or general
  141. exceptions, as in the cases here.
  142. .. testcode::
  143. @retry(retry=retry_if_exception_type(IOError))
  144. def might_io_error():
  145. print("Retry forever with no wait if an IOError occurs, raise any other errors")
  146. raise Exception
  147. We can also use the result of the function to alter the behavior of retrying.
  148. .. testcode::
  149. def is_none_p(value):
  150. """Return True if value is None"""
  151. return value is None
  152. @retry(retry=retry_if_result(is_none_p))
  153. def might_return_none():
  154. print("Retry with no wait if return value is None")
  155. We can also combine several conditions:
  156. .. testcode::
  157. def is_none_p(value):
  158. """Return True if value is None"""
  159. return value is None
  160. @retry(retry=(retry_if_result(is_none_p) | retry_if_exception_type()))
  161. def might_return_none():
  162. print("Retry forever ignoring Exceptions with no wait if return value is None")
  163. Any combination of stop, wait, etc. is also supported to give you the freedom
  164. to mix and match.
  165. It's also possible to retry explicitly at any time by raising the `TryAgain`
  166. exception:
  167. .. testcode::
  168. @retry
  169. def do_something():
  170. result = something_else()
  171. if result == 23:
  172. raise TryAgain
  173. Error Handling
  174. ~~~~~~~~~~~~~~
  175. While callables that "timeout" retrying raise a `RetryError` by default,
  176. we can reraise the last attempt's exception if needed:
  177. .. testcode::
  178. @retry(reraise=True, stop=stop_after_attempt(3))
  179. def raise_my_exception():
  180. raise MyException("Fail")
  181. try:
  182. raise_my_exception()
  183. except MyException:
  184. # timed out retrying
  185. pass
  186. Before and After Retry, and Logging
  187. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  188. It's possible to execute an action before any attempt of calling the function
  189. by using the before callback function:
  190. .. testcode::
  191. import logging
  192. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  193. logger = logging.getLogger(__name__)
  194. @retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
  195. def raise_my_exception():
  196. raise MyException("Fail")
  197. In the same spirit, It's possible to execute after a call that failed:
  198. .. testcode::
  199. import logging
  200. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  201. logger = logging.getLogger(__name__)
  202. @retry(stop=stop_after_attempt(3), after=after_log(logger, logging.DEBUG))
  203. def raise_my_exception():
  204. raise MyException("Fail")
  205. It's also possible to only log failures that are going to be retried. Normally
  206. retries happen after a wait interval, so the keyword argument is called
  207. ``before_sleep``:
  208. .. testcode::
  209. import logging
  210. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  211. logger = logging.getLogger(__name__)
  212. @retry(stop=stop_after_attempt(3),
  213. before_sleep=before_sleep_log(logger, logging.DEBUG))
  214. def raise_my_exception():
  215. raise MyException("Fail")
  216. Statistics
  217. ~~~~~~~~~~
  218. You can access the statistics about the retry made over a function by using the
  219. `retry` attribute attached to the function and its `statistics` attribute:
  220. .. testcode::
  221. @retry(stop=stop_after_attempt(3))
  222. def raise_my_exception():
  223. raise MyException("Fail")
  224. try:
  225. raise_my_exception()
  226. except Exception:
  227. pass
  228. print(raise_my_exception.retry.statistics)
  229. .. testoutput::
  230. :hide:
  231. ...
  232. Custom Callbacks
  233. ~~~~~~~~~~~~~~~~
  234. You can also define your own callbacks. The callback should accept one
  235. parameter called ``retry_state`` that contains all information about current
  236. retry invocation.
  237. For example, you can call a custom callback function after all retries failed,
  238. without raising an exception (or you can re-raise or do anything really)
  239. .. testcode::
  240. def return_last_value(retry_state):
  241. """return the result of the last call attempt"""
  242. return retry_state.outcome.result()
  243. def is_false(value):
  244. """Return True if value is False"""
  245. return value is False
  246. # will return False after trying 3 times to get a different result
  247. @retry(stop=stop_after_attempt(3),
  248. retry_error_callback=return_last_value,
  249. retry=retry_if_result(is_false))
  250. def eventually_return_false():
  251. return False
  252. RetryCallState
  253. ~~~~~~~~~~~~~~
  254. ``retry_state`` argument is an object of `RetryCallState` class:
  255. .. autoclass:: tenacity.RetryCallState
  256. Constant attributes:
  257. .. autoattribute:: start_time(float)
  258. :annotation:
  259. .. autoattribute:: retry_object(BaseRetrying)
  260. :annotation:
  261. .. autoattribute:: fn(callable)
  262. :annotation:
  263. .. autoattribute:: args(tuple)
  264. :annotation:
  265. .. autoattribute:: kwargs(dict)
  266. :annotation:
  267. Variable attributes:
  268. .. autoattribute:: attempt_number(int)
  269. :annotation:
  270. .. autoattribute:: outcome(tenacity.Future or None)
  271. :annotation:
  272. .. autoattribute:: outcome_timestamp(float or None)
  273. :annotation:
  274. .. autoattribute:: idle_for(float)
  275. :annotation:
  276. .. autoattribute:: next_action(tenacity.RetryAction or None)
  277. :annotation:
  278. Other Custom Callbacks
  279. ~~~~~~~~~~~~~~~~~~~~~~
  280. It's also possible to define custom callbacks for other keyword arguments.
  281. .. function:: my_stop(retry_state)
  282. :param RetryState retry_state: info about current retry invocation
  283. :return: whether or not retrying should stop
  284. :rtype: bool
  285. .. function:: my_wait(retry_state)
  286. :param RetryState retry_state: info about current retry invocation
  287. :return: number of seconds to wait before next retry
  288. :rtype: float
  289. .. function:: my_retry(retry_state)
  290. :param RetryState retry_state: info about current retry invocation
  291. :return: whether or not retrying should continue
  292. :rtype: bool
  293. .. function:: my_before(retry_state)
  294. :param RetryState retry_state: info about current retry invocation
  295. .. function:: my_after(retry_state)
  296. :param RetryState retry_state: info about current retry invocation
  297. .. function:: my_before_sleep(retry_state)
  298. :param RetryState retry_state: info about current retry invocation
  299. Here's an example with a custom ``before_sleep`` function:
  300. .. testcode::
  301. import logging
  302. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  303. logger = logging.getLogger(__name__)
  304. def my_before_sleep(retry_state):
  305. if retry_state.attempt_number < 1:
  306. loglevel = logging.INFO
  307. else:
  308. loglevel = logging.WARNING
  309. logger.log(
  310. loglevel, 'Retrying %s: attempt %s ended with: %s',
  311. retry_state.fn, retry_state.attempt_number, retry_state.outcome)
  312. @retry(stop=stop_after_attempt(3), before_sleep=my_before_sleep)
  313. def raise_my_exception():
  314. raise MyException("Fail")
  315. try:
  316. raise_my_exception()
  317. except RetryError:
  318. pass
  319. Changing Arguments at Run Time
  320. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  321. You can change the arguments of a retry decorator as needed when calling it by
  322. using the `retry_with` function attached to the wrapped function:
  323. .. testcode::
  324. @retry(stop=stop_after_attempt(3))
  325. def raise_my_exception():
  326. raise MyException("Fail")
  327. try:
  328. raise_my_exception.retry_with(stop=stop_after_attempt(4))()
  329. except Exception:
  330. pass
  331. print(raise_my_exception.retry.statistics)
  332. .. testoutput::
  333. :hide:
  334. ...
  335. If you want to use variables to set up the retry parameters, you don't have
  336. to use the `retry` decorator - you can instead use `Retrying` directly:
  337. .. testcode::
  338. def never_good_enough(arg1):
  339. raise Exception('Invalid argument: {}'.format(arg1))
  340. def try_never_good_enough(max_attempts=3):
  341. retryer = Retrying(stop=stop_after_attempt(max_attempts), reraise=True)
  342. retryer(never_good_enough, 'I really do try')
  343. Retrying code block
  344. ~~~~~~~~~~~~~~~~~~~
  345. Tenacity allows you to retry a code block without the need to wraps it in an
  346. isolated function. This makes it easy to isolate failing block while sharing
  347. context. The trick is to combine a for loop and a context manager.
  348. .. testcode::
  349. from tenacity import Retrying, RetryError, stop_after_attempt
  350. try:
  351. for attempt in Retrying(stop=stop_after_attempt(3)):
  352. with attempt:
  353. raise Exception('My code is failing!')
  354. except RetryError:
  355. pass
  356. You can configure every details of retry policy by configuring the Retrying
  357. object.
  358. With async code you can use AsyncRetrying.
  359. .. testcode::
  360. from tenacity import AsyncRetrying, RetryError, stop_after_attempt
  361. async def function():
  362. try:
  363. async for attempt in AsyncRetrying(stop=stop_after_attempt(3)):
  364. with attempt:
  365. raise Exception('My code is failing!')
  366. except RetryError:
  367. pass
  368. Async and retry
  369. ~~~~~~~~~~~~~~~
  370. Finally, ``retry`` works also on asyncio and Tornado (>= 4.5) coroutines.
  371. Sleeps are done asynchronously too.
  372. .. code-block:: python
  373. @retry
  374. async def my_async_function(loop):
  375. await loop.getaddrinfo('8.8.8.8', 53)
  376. .. code-block:: python
  377. @retry
  378. @tornado.gen.coroutine
  379. def my_async_function(http_client, url):
  380. yield http_client.fetch(url)
  381. You can even use alternative event loops such as `curio` or `Trio` by passing the correct sleep function:
  382. .. code-block:: python
  383. @retry(sleep=trio.sleep)
  384. async def my_async_function(loop):
  385. await asks.get('https://example.org')
  386. Contribute
  387. ----------
  388. #. Check for open issues or open a fresh issue to start a discussion around a
  389. feature idea or a bug.
  390. #. Fork `the repository`_ on GitHub to start making your changes to the
  391. **master** branch (or branch off of it).
  392. #. Write a test which shows that the bug was fixed or that the feature works as
  393. expected.
  394. #. Add a `changelog <#Changelogs>`_
  395. #. Make the docs better (or more detailed, or more easier to read, or ...)
  396. .. _`the repository`: https://github.com/jd/tenacity
  397. Changelogs
  398. ~~~~~~~~~~
  399. `reno`_ is used for managing changelogs. Take a look at their usage docs.
  400. The doc generation will automatically compile the changelogs. You just need to add them.
  401. .. code-block:: sh
  402. # Opens a template file in an editor
  403. tox -e reno -- new some-slug-for-my-change --edit
  404. .. _`reno`: https://docs.openstack.org/reno/latest/user/usage.html