README.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. You can combine several stop conditions by using the `|` operator:
  89. .. testcode::
  90. @retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
  91. def stop_after_10_s_or_5_retries():
  92. print("Stopping after 10 seconds or 5 retries")
  93. raise Exception
  94. Waiting before retrying
  95. ~~~~~~~~~~~~~~~~~~~~~~~
  96. Most things don't like to be polled as fast as possible, so let's just wait 2
  97. seconds between retries.
  98. .. testcode::
  99. @retry(wait=wait_fixed(2))
  100. def wait_2_s():
  101. print("Wait 2 second between retries")
  102. raise Exception
  103. Some things perform best with a bit of randomness injected.
  104. .. testcode::
  105. @retry(wait=wait_random(min=1, max=2))
  106. def wait_random_1_to_2_s():
  107. print("Randomly wait 1 to 2 seconds between retries")
  108. raise Exception
  109. Then again, it's hard to beat exponential backoff when retrying distributed
  110. services and other remote endpoints.
  111. .. testcode::
  112. @retry(wait=wait_exponential(multiplier=1, min=4, max=10))
  113. def wait_exponential_1():
  114. print("Wait 2^x * 1 second between each retry starting with 4 seconds, then up to 10 seconds, then 10 seconds afterwards")
  115. raise Exception
  116. Then again, it's also hard to beat combining fixed waits and jitter (to
  117. help avoid thundering herds) when retrying distributed services and other
  118. remote endpoints.
  119. .. testcode::
  120. @retry(wait=wait_fixed(3) + wait_random(0, 2))
  121. def wait_fixed_jitter():
  122. print("Wait at least 3 seconds, and add up to 2 seconds of random delay")
  123. raise Exception
  124. When multiple processes are in contention for a shared resource, exponentially
  125. increasing jitter helps minimise collisions.
  126. .. testcode::
  127. @retry(wait=wait_random_exponential(multiplier=1, max=60))
  128. def wait_exponential_jitter():
  129. 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")
  130. raise Exception
  131. Sometimes it's necessary to build a chain of backoffs.
  132. .. testcode::
  133. @retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +
  134. [wait_fixed(7) for i in range(2)] +
  135. [wait_fixed(9)]))
  136. def wait_fixed_chained():
  137. print("Wait 3s for 3 attempts, 7s for the next 2 attempts and 9s for all attempts thereafter")
  138. raise Exception
  139. Whether to retry
  140. ~~~~~~~~~~~~~~~~
  141. We have a few options for dealing with retries that raise specific or general
  142. exceptions, as in the cases here.
  143. .. testcode::
  144. class ClientError(Exception):
  145. """Some type of client error."""
  146. @retry(retry=retry_if_exception_type(IOError))
  147. def might_io_error():
  148. print("Retry forever with no wait if an IOError occurs, raise any other errors")
  149. raise Exception
  150. @retry(retry=retry_if_not_exception_type(ClientError))
  151. def might_client_error():
  152. print("Retry forever with no wait if any error other than ClientError occurs. Immediately raise ClientError.")
  153. raise Exception
  154. We can also use the result of the function to alter the behavior of retrying.
  155. .. testcode::
  156. def is_none_p(value):
  157. """Return True if value is None"""
  158. return value is None
  159. @retry(retry=retry_if_result(is_none_p))
  160. def might_return_none():
  161. print("Retry with no wait if return value is None")
  162. See also these methods:
  163. .. testcode::
  164. retry_if_exception
  165. retry_if_exception_type
  166. retry_if_not_exception_type
  167. retry_unless_exception_type
  168. retry_if_result
  169. retry_if_not_result
  170. retry_if_exception_message
  171. retry_if_not_exception_message
  172. retry_any
  173. retry_all
  174. We can also combine several conditions:
  175. .. testcode::
  176. def is_none_p(value):
  177. """Return True if value is None"""
  178. return value is None
  179. @retry(retry=(retry_if_result(is_none_p) | retry_if_exception_type()))
  180. def might_return_none():
  181. print("Retry forever ignoring Exceptions with no wait if return value is None")
  182. Any combination of stop, wait, etc. is also supported to give you the freedom
  183. to mix and match.
  184. It's also possible to retry explicitly at any time by raising the `TryAgain`
  185. exception:
  186. .. testcode::
  187. @retry
  188. def do_something():
  189. result = something_else()
  190. if result == 23:
  191. raise TryAgain
  192. Error Handling
  193. ~~~~~~~~~~~~~~
  194. Normally when your function fails its final time (and will not be retried again based on your settings),
  195. a `RetryError` is raised. The exception your code encountered will be shown somewhere in the *middle*
  196. of the stack trace.
  197. If you would rather see the exception your code encountered at the *end* of the stack trace (where it
  198. is most visible), you can set `reraise=True`.
  199. .. testcode::
  200. @retry(reraise=True, stop=stop_after_attempt(3))
  201. def raise_my_exception():
  202. raise MyException("Fail")
  203. try:
  204. raise_my_exception()
  205. except MyException:
  206. # timed out retrying
  207. pass
  208. Before and After Retry, and Logging
  209. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  210. It's possible to execute an action before any attempt of calling the function
  211. by using the before callback function:
  212. .. testcode::
  213. import logging
  214. import sys
  215. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  216. logger = logging.getLogger(__name__)
  217. @retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
  218. def raise_my_exception():
  219. raise MyException("Fail")
  220. In the same spirit, It's possible to execute after a call that failed:
  221. .. testcode::
  222. import logging
  223. import sys
  224. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  225. logger = logging.getLogger(__name__)
  226. @retry(stop=stop_after_attempt(3), after=after_log(logger, logging.DEBUG))
  227. def raise_my_exception():
  228. raise MyException("Fail")
  229. It's also possible to only log failures that are going to be retried. Normally
  230. retries happen after a wait interval, so the keyword argument is called
  231. ``before_sleep``:
  232. .. testcode::
  233. import logging
  234. import sys
  235. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  236. logger = logging.getLogger(__name__)
  237. @retry(stop=stop_after_attempt(3),
  238. before_sleep=before_sleep_log(logger, logging.DEBUG))
  239. def raise_my_exception():
  240. raise MyException("Fail")
  241. Statistics
  242. ~~~~~~~~~~
  243. You can access the statistics about the retry made over a function by using the
  244. `retry` attribute attached to the function and its `statistics` attribute:
  245. .. testcode::
  246. @retry(stop=stop_after_attempt(3))
  247. def raise_my_exception():
  248. raise MyException("Fail")
  249. try:
  250. raise_my_exception()
  251. except Exception:
  252. pass
  253. print(raise_my_exception.retry.statistics)
  254. .. testoutput::
  255. :hide:
  256. ...
  257. Custom Callbacks
  258. ~~~~~~~~~~~~~~~~
  259. You can also define your own callbacks. The callback should accept one
  260. parameter called ``retry_state`` that contains all information about current
  261. retry invocation.
  262. For example, you can call a custom callback function after all retries failed,
  263. without raising an exception (or you can re-raise or do anything really)
  264. .. testcode::
  265. def return_last_value(retry_state):
  266. """return the result of the last call attempt"""
  267. return retry_state.outcome.result()
  268. def is_false(value):
  269. """Return True if value is False"""
  270. return value is False
  271. # will return False after trying 3 times to get a different result
  272. @retry(stop=stop_after_attempt(3),
  273. retry_error_callback=return_last_value,
  274. retry=retry_if_result(is_false))
  275. def eventually_return_false():
  276. return False
  277. RetryCallState
  278. ~~~~~~~~~~~~~~
  279. ``retry_state`` argument is an object of `RetryCallState` class:
  280. .. autoclass:: tenacity.RetryCallState
  281. Constant attributes:
  282. .. autoattribute:: start_time(float)
  283. :annotation:
  284. .. autoattribute:: retry_object(BaseRetrying)
  285. :annotation:
  286. .. autoattribute:: fn(callable)
  287. :annotation:
  288. .. autoattribute:: args(tuple)
  289. :annotation:
  290. .. autoattribute:: kwargs(dict)
  291. :annotation:
  292. Variable attributes:
  293. .. autoattribute:: attempt_number(int)
  294. :annotation:
  295. .. autoattribute:: outcome(tenacity.Future or None)
  296. :annotation:
  297. .. autoattribute:: outcome_timestamp(float or None)
  298. :annotation:
  299. .. autoattribute:: idle_for(float)
  300. :annotation:
  301. .. autoattribute:: next_action(tenacity.RetryAction or None)
  302. :annotation:
  303. Other Custom Callbacks
  304. ~~~~~~~~~~~~~~~~~~~~~~
  305. It's also possible to define custom callbacks for other keyword arguments.
  306. .. function:: my_stop(retry_state)
  307. :param RetryState retry_state: info about current retry invocation
  308. :return: whether or not retrying should stop
  309. :rtype: bool
  310. .. function:: my_wait(retry_state)
  311. :param RetryState retry_state: info about current retry invocation
  312. :return: number of seconds to wait before next retry
  313. :rtype: float
  314. .. function:: my_retry(retry_state)
  315. :param RetryState retry_state: info about current retry invocation
  316. :return: whether or not retrying should continue
  317. :rtype: bool
  318. .. function:: my_before(retry_state)
  319. :param RetryState retry_state: info about current retry invocation
  320. .. function:: my_after(retry_state)
  321. :param RetryState retry_state: info about current retry invocation
  322. .. function:: my_before_sleep(retry_state)
  323. :param RetryState retry_state: info about current retry invocation
  324. Here's an example with a custom ``before_sleep`` function:
  325. .. testcode::
  326. import logging
  327. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  328. logger = logging.getLogger(__name__)
  329. def my_before_sleep(retry_state):
  330. if retry_state.attempt_number < 1:
  331. loglevel = logging.INFO
  332. else:
  333. loglevel = logging.WARNING
  334. logger.log(
  335. loglevel, 'Retrying %s: attempt %s ended with: %s',
  336. retry_state.fn, retry_state.attempt_number, retry_state.outcome)
  337. @retry(stop=stop_after_attempt(3), before_sleep=my_before_sleep)
  338. def raise_my_exception():
  339. raise MyException("Fail")
  340. try:
  341. raise_my_exception()
  342. except RetryError:
  343. pass
  344. Changing Arguments at Run Time
  345. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  346. You can change the arguments of a retry decorator as needed when calling it by
  347. using the `retry_with` function attached to the wrapped function:
  348. .. testcode::
  349. @retry(stop=stop_after_attempt(3))
  350. def raise_my_exception():
  351. raise MyException("Fail")
  352. try:
  353. raise_my_exception.retry_with(stop=stop_after_attempt(4))()
  354. except Exception:
  355. pass
  356. print(raise_my_exception.retry.statistics)
  357. .. testoutput::
  358. :hide:
  359. ...
  360. If you want to use variables to set up the retry parameters, you don't have
  361. to use the `retry` decorator - you can instead use `Retrying` directly:
  362. .. testcode::
  363. def never_good_enough(arg1):
  364. raise Exception('Invalid argument: {}'.format(arg1))
  365. def try_never_good_enough(max_attempts=3):
  366. retryer = Retrying(stop=stop_after_attempt(max_attempts), reraise=True)
  367. retryer(never_good_enough, 'I really do try')
  368. Retrying code block
  369. ~~~~~~~~~~~~~~~~~~~
  370. Tenacity allows you to retry a code block without the need to wraps it in an
  371. isolated function. This makes it easy to isolate failing block while sharing
  372. context. The trick is to combine a for loop and a context manager.
  373. .. testcode::
  374. from tenacity import Retrying, RetryError, stop_after_attempt
  375. try:
  376. for attempt in Retrying(stop=stop_after_attempt(3)):
  377. with attempt:
  378. raise Exception('My code is failing!')
  379. except RetryError:
  380. pass
  381. You can configure every details of retry policy by configuring the Retrying
  382. object.
  383. With async code you can use AsyncRetrying.
  384. .. testcode::
  385. from tenacity import AsyncRetrying, RetryError, stop_after_attempt
  386. async def function():
  387. try:
  388. async for attempt in AsyncRetrying(stop=stop_after_attempt(3)):
  389. with attempt:
  390. raise Exception('My code is failing!')
  391. except RetryError:
  392. pass
  393. In both cases, you may want to set the result to the attempt so it's available
  394. in retry strategies like ``retry_if_result``. This can be done accessing the
  395. ``retry_state`` property:
  396. .. testcode::
  397. from tenacity import AsyncRetrying, retry_if_result
  398. async def function():
  399. async for attempt in AsyncRetrying(retry=retry_if_result(lambda x: x < 3)):
  400. with attempt:
  401. result = 1 # Some complex calculation, function call, etc.
  402. if not attempt.retry_state.outcome.failed:
  403. attempt.retry_state.set_result(result)
  404. return result
  405. Async and retry
  406. ~~~~~~~~~~~~~~~
  407. Finally, ``retry`` works also on asyncio and Tornado (>= 4.5) coroutines.
  408. Sleeps are done asynchronously too.
  409. .. code-block:: python
  410. @retry
  411. async def my_async_function(loop):
  412. await loop.getaddrinfo('8.8.8.8', 53)
  413. .. code-block:: python
  414. @retry
  415. @tornado.gen.coroutine
  416. def my_async_function(http_client, url):
  417. yield http_client.fetch(url)
  418. You can even use alternative event loops such as `curio` or `Trio` by passing the correct sleep function:
  419. .. code-block:: python
  420. @retry(sleep=trio.sleep)
  421. async def my_async_function(loop):
  422. await asks.get('https://example.org')
  423. Contribute
  424. ----------
  425. #. Check for open issues or open a fresh issue to start a discussion around a
  426. feature idea or a bug.
  427. #. Fork `the repository`_ on GitHub to start making your changes to the
  428. **main** branch (or branch off of it).
  429. #. Write a test which shows that the bug was fixed or that the feature works as
  430. expected.
  431. #. Add a `changelog <#Changelogs>`_
  432. #. Make the docs better (or more detailed, or more easier to read, or ...)
  433. .. _`the repository`: https://github.com/jd/tenacity
  434. Changelogs
  435. ~~~~~~~~~~
  436. `reno`_ is used for managing changelogs. Take a look at their usage docs.
  437. The doc generation will automatically compile the changelogs. You just need to add them.
  438. .. code-block:: sh
  439. # Opens a template file in an editor
  440. tox -e reno -- new some-slug-for-my-change --edit
  441. .. _`reno`: https://docs.openstack.org/reno/latest/user/usage.html