README.rst 17 KB

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