METADATA 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. Metadata-Version: 2.1
  2. Name: tenacity
  3. Version: 5.0.2
  4. Summary: Retry code until it succeeeds
  5. Home-page: https://github.com/jd/tenacity
  6. Author: Julien Danjou
  7. Author-email: julien@danjou.info
  8. License: Apache 2.0
  9. Platform: UNKNOWN
  10. Classifier: Intended Audience :: Developers
  11. Classifier: License :: OSI Approved :: Apache Software License
  12. Classifier: Programming Language :: Python
  13. Classifier: Programming Language :: Python :: 2.7
  14. Classifier: Programming Language :: Python :: 3.5
  15. Classifier: Programming Language :: Python :: 3.6
  16. Classifier: Topic :: Utilities
  17. Requires-Dist: six (>=1.9.0)
  18. Requires-Dist: futures (>=3.0); (python_version=='2.7')
  19. Requires-Dist: monotonic (>=0.6); (python_version=='2.7')
  20. Tenacity
  21. ========
  22. .. image:: https://img.shields.io/pypi/v/tenacity.svg
  23. :target: https://pypi.python.org/pypi/tenacity
  24. .. image:: https://img.shields.io/travis/jd/tenacity.svg
  25. :target: https://travis-ci.org/jd/tenacity
  26. .. image:: https://img.shields.io/badge/SayThanks.io-%E2%98%BC-1EAEDB.svg
  27. :target: https://saythanks.io/to/jd
  28. Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in
  29. Python, to simplify the task of adding retry behavior to just about anything.
  30. It originates from `a fork of retrying
  31. <https://github.com/rholder/retrying/issues/65>`_ which is sadly no longer
  32. `maintained <https://julien.danjou.info/python-tenacity/>`_. Tenacity isn't
  33. api compatible with retrying but adds significant new functionality and
  34. fixes a number of longstanding bugs.
  35. The simplest use case is retrying a flaky function whenever an `Exception`
  36. occurs until a value is returned.
  37. .. testcode::
  38. import random
  39. from tenacity import retry
  40. @retry
  41. def do_something_unreliable():
  42. if random.randint(0, 10) > 1:
  43. raise IOError("Broken sauce, everything is hosed!!!111one")
  44. else:
  45. return "Awesome sauce!"
  46. print(do_something_unreliable())
  47. .. testoutput::
  48. :hide:
  49. Awesome sauce!
  50. Features
  51. --------
  52. - Generic Decorator API
  53. - Specify stop condition (i.e. limit by number of attempts)
  54. - Specify wait condition (i.e. exponential backoff sleeping between attempts)
  55. - Customize retrying on Exceptions
  56. - Customize retrying on expected returned result
  57. - Retry on coroutines
  58. Installation
  59. ------------
  60. To install *tenacity*, simply:
  61. .. code-block:: bash
  62. $ pip install tenacity
  63. Examples
  64. ----------
  65. Basic Retry
  66. ~~~~~~~~~~~
  67. .. testsetup:: *
  68. import logging
  69. from tenacity import *
  70. class MyException(Exception):
  71. pass
  72. As you saw above, the default behavior is to retry forever without waiting when
  73. an exception is raised.
  74. .. testcode::
  75. @retry
  76. def never_give_up_never_surrender():
  77. print("Retry forever ignoring Exceptions, don't wait between retries")
  78. raise Exception
  79. Stopping
  80. ~~~~~~~~
  81. Let's be a little less persistent and set some boundaries, such as the number
  82. of attempts before giving up.
  83. .. testcode::
  84. @retry(stop=stop_after_attempt(7))
  85. def stop_after_7_attempts():
  86. print("Stopping after 7 attempts")
  87. raise Exception
  88. We don't have all day, so let's set a boundary for how long we should be
  89. retrying stuff.
  90. .. testcode::
  91. @retry(stop=stop_after_delay(10))
  92. def stop_after_10_s():
  93. print("Stopping after 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. @retry(retry=retry_if_exception_type(IOError))
  152. def might_io_error():
  153. print("Retry forever with no wait if an IOError occurs, raise any other errors")
  154. raise Exception
  155. We can also use the result of the function to alter the behavior of retrying.
  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))
  161. def might_return_none():
  162. print("Retry with no wait if return value is None")
  163. We can also combine several conditions:
  164. .. testcode::
  165. def is_none_p(value):
  166. """Return True if value is None"""
  167. return value is None
  168. @retry(retry=(retry_if_result(is_none_p) | retry_if_exception_type()))
  169. def might_return_none():
  170. print("Retry forever ignoring Exceptions with no wait if return value is None")
  171. Any combination of stop, wait, etc. is also supported to give you the freedom
  172. to mix and match.
  173. It's also possible to retry explicitly at any time by raising the `TryAgain`
  174. exception:
  175. .. testcode::
  176. @retry
  177. def do_something():
  178. result = something_else()
  179. if result == 23:
  180. raise TryAgain
  181. Error Handling
  182. ~~~~~~~~~~~~~~
  183. While callables that "timeout" retrying raise a `RetryError` by default,
  184. we can reraise the last attempt's exception if needed:
  185. .. testcode::
  186. @retry(reraise=True, stop=stop_after_attempt(3))
  187. def raise_my_exception():
  188. raise MyException("Fail")
  189. try:
  190. raise_my_exception()
  191. except MyException:
  192. # timed out retrying
  193. pass
  194. Before and After Retry, and Logging
  195. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  196. It's possible to execute an action before any attempt of calling the function
  197. by using the before callback function:
  198. .. testcode::
  199. logger = logging.getLogger(__name__)
  200. @retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
  201. def raise_my_exception():
  202. raise MyException("Fail")
  203. In the same spirit, It's possible to execute after a call that failed:
  204. .. testcode::
  205. logger = logging.getLogger(__name__)
  206. @retry(stop=stop_after_attempt(3), after=after_log(logger, logging.DEBUG))
  207. def raise_my_exception():
  208. raise MyException("Fail")
  209. It's also possible to only log failures that are going to be retried. Normally
  210. retries happen after a wait interval, so the keyword argument is called
  211. ``before_sleep``:
  212. .. testcode::
  213. logger = logging.getLogger(__name__)
  214. @retry(stop=stop_after_attempt(3),
  215. before_sleep=before_sleep_log(logger, logging.DEBUG))
  216. def raise_my_exception():
  217. raise MyException("Fail")
  218. Statistics
  219. ~~~~~~~~~~
  220. You can access the statistics about the retry made over a function by using the
  221. `retry` attribute attached to the function and its `statistics` attribute:
  222. .. testcode::
  223. @retry(stop=stop_after_attempt(3))
  224. def raise_my_exception():
  225. raise MyException("Fail")
  226. try:
  227. raise_my_exception()
  228. except Exception:
  229. pass
  230. print(raise_my_exception.retry.statistics)
  231. .. testoutput::
  232. :hide:
  233. ...
  234. Custom Callbacks
  235. ~~~~~~~~~~~~~~~~
  236. You can also define your own callbacks. The callback should accept one
  237. parameter called ``retry_state`` that contains all information about current
  238. retry invocation.
  239. For example, you can call a custom callback function after all retries failed,
  240. without raising an exception (or you can re-raise or do anything really)
  241. .. testcode::
  242. def return_last_value(retry_state):
  243. """return the result of the last call attempt"""
  244. return retry_state.last_outcome.result()
  245. def is_false(value):
  246. """Return True if value is False"""
  247. return value is False
  248. # will return False after trying 3 times to get a different result
  249. @retry(stop=stop_after_attempt(3),
  250. retry_error_callback=return_last_value,
  251. retry=retry_if_result(is_false))
  252. def eventually_return_false():
  253. return False
  254. .. note::
  255. Calling the parameter ``retry_state`` is important, because this is how
  256. *tenacity* internally distinguishes callbacks from their :ref:`deprecated
  257. counterparts <deprecated-callbacks>`.
  258. RetryCallState
  259. ~~~~~~~~~~~~~~
  260. ``retry_state`` argument is an object of `RetryCallState` class:
  261. .. autoclass:: tenacity.RetryCallState
  262. Constant attributes:
  263. .. autoinstanceattribute:: start_time(float)
  264. :annotation:
  265. .. autoinstanceattribute:: retry_object(BaseRetrying)
  266. :annotation:
  267. .. autoinstanceattribute:: fn(callable)
  268. :annotation:
  269. .. autoinstanceattribute:: args(tuple)
  270. :annotation:
  271. .. autoinstanceattribute:: kwargs(dict)
  272. :annotation:
  273. Variable attributes:
  274. .. autoinstanceattribute:: attempt_number(int)
  275. :annotation:
  276. .. autoinstanceattribute:: outcome(tenacity.Future or None)
  277. :annotation:
  278. .. autoinstanceattribute:: outcome_timestamp(float or None)
  279. :annotation:
  280. .. autoinstanceattribute:: idle_for(float)
  281. :annotation:
  282. .. autoinstanceattribute:: next_action(tenacity.RetryAction or None)
  283. :annotation:
  284. Other Custom Callbacks
  285. ~~~~~~~~~~~~~~~~~~~~~~
  286. It's also possible to define custom callbacks for other keyword arguments.
  287. .. function:: my_stop(retry_state)
  288. :param RetryState retry_state: info about current retry invocation
  289. :return: whether or not retrying should stop
  290. :rtype: bool
  291. .. function:: my_wait(retry_state)
  292. :param RetryState retry_state: info about current retry invocation
  293. :return: number of seconds to wait before next retry
  294. :rtype: float
  295. .. function:: my_retry(retry_state)
  296. :param RetryState retry_state: info about current retry invocation
  297. :return: whether or not retrying should continue
  298. :rtype: bool
  299. .. function:: my_before(retry_state)
  300. :param RetryState retry_state: info about current retry invocation
  301. .. function:: my_after(retry_state)
  302. :param RetryState retry_state: info about current retry invocation
  303. .. function:: my_before_sleep(retry_state)
  304. :param RetryState retry_state: info about current retry invocation
  305. Here's an example with a custom ``before_sleep`` function:
  306. .. testcode::
  307. logger = logging.getLogger(__name__)
  308. def my_before_sleep(retry_state):
  309. if retry_state.attempt_number < 1:
  310. loglevel = logging.INFO
  311. else:
  312. loglevel = logging.WARNING
  313. logger.log(
  314. loglevel, 'Retrying %s: attempt %s ended with: %s',
  315. retry_state.fn, retry_state.attempt_number, retry_state.outcome)
  316. @retry(stop=stop_after_attempt(3), before_sleep=my_before_sleep)
  317. def raise_my_exception():
  318. raise MyException("Fail")
  319. try:
  320. raise_my_exception()
  321. except RetryError:
  322. pass
  323. .. _deprecated-callbacks:
  324. .. note::
  325. It was also possible to define custom callbacks before, but they accepted
  326. varying parameter sets and none of those provided full state. The old way is
  327. deprecated, but kept for backward compatibility.
  328. .. function:: my_stop(previous_attempt_number, delay_since_first_attempt)
  329. *deprecated*
  330. :param previous_attempt_number: the number of current attempt
  331. :type previous_attempt_number: int
  332. :param delay_since_first_attempt: interval in seconds between the
  333. beginning of first attempt and current time
  334. :type delay_since_first_attempt: float
  335. :rtype: bool
  336. .. function:: my_wait(previous_attempt_number, delay_since_first_attempt [, last_result])
  337. *deprecated*
  338. :param previous_attempt_number: the number of current attempt
  339. :type previous_attempt_number: int
  340. :param delay_since_first_attempt: interval in seconds between the
  341. beginning of first attempt and current time
  342. :type delay_since_first_attempt: float
  343. :param tenacity.Future last_result: current outcome
  344. :return: number of seconds to wait before next retry
  345. :rtype: float
  346. .. function:: my_retry(attempt)
  347. *deprecated*
  348. :param tenacity.Future attempt: current outcome
  349. :return: whether or not retrying should continue
  350. :rtype: bool
  351. .. function:: my_before(func, trial_number)
  352. *deprecated*
  353. :param callable func: function whose outcome is to be retried
  354. :param int trial_number: the number of current attempt
  355. .. function:: my_after(func, trial_number, trial_time_taken)
  356. *deprecated*
  357. :param callable func: function whose outcome is to be retried
  358. :param int trial_number: the number of current attempt
  359. :param float trial_time_taken: interval in seconds between the beginning
  360. of first attempt and current time
  361. .. function:: my_before_sleep(func, sleep, last_result)
  362. *deprecated*
  363. :param callable func: function whose outcome is to be retried
  364. :param float sleep: number of seconds to wait until next retry
  365. :param tenacity.Future last_result: current outcome
  366. .. testcode::
  367. logger = logging.getLogger(__name__)
  368. def my_before_sleep(retry_object, sleep, last_result):
  369. logger.warning(
  370. 'Retrying %s: last_result=%s, retrying in %s seconds...',
  371. retry_object.fn, last_result, sleep)
  372. @retry(stop=stop_after_attempt(3), before_sleep=my_before_sleep)
  373. def raise_my_exception():
  374. raise MyException("Fail")
  375. try:
  376. raise_my_exception()
  377. except RetryError:
  378. pass
  379. Changing Arguments at Run Time
  380. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  381. You can change the arguments of a retry decorator as needed when calling it by
  382. using the `retry_with` function attached to the wrapped function:
  383. .. testcode::
  384. @retry(stop=stop_after_attempt(3))
  385. def raise_my_exception():
  386. raise MyException("Fail")
  387. try:
  388. raise_my_exception.retry_with(stop=stop_after_attempt(4))()
  389. except Exception:
  390. pass
  391. print(raise_my_exception.retry.statistics)
  392. .. testoutput::
  393. :hide:
  394. ...
  395. If you want to use variables to set up the retry parameters, you don't have
  396. to use the `retry` decorator - you can instead use `Retrying` directly:
  397. .. testcode::
  398. def never_good_enough(arg1):
  399. raise Exception('Invalid argument: {}'.format(arg1))
  400. def try_never_good_enough(max_attempts=3):
  401. retryer = Retrying(stop=stop_after_attempt(max_attempts), reraise=True)
  402. retryer(never_good_enough, 'I really do try')
  403. Async and retry
  404. ~~~~~~~~~~~~~~~
  405. Finally, ``retry`` works also on asyncio and Tornado (>= 4.5) coroutines.
  406. Sleeps are done asynchronously too.
  407. .. code-block:: python
  408. @retry
  409. async def my_async_function(loop):
  410. await loop.getaddrinfo('8.8.8.8', 53)
  411. .. code-block:: python
  412. @retry
  413. @tornado.gen.coroutine
  414. def my_async_function(http_client, url):
  415. yield http_client.fetch(url)
  416. You can even use alternative event loops such as `curio` or `Trio` by passing the correct sleep function:
  417. .. code-block:: python
  418. @retry(sleep=trio.sleep)
  419. async def my_async_function(loop):
  420. await asks.get('https://example.org')
  421. Contribute
  422. ----------
  423. #. Check for open issues or open a fresh issue to start a discussion around a
  424. feature idea or a bug.
  425. #. Fork `the repository`_ on GitHub to start making your changes to the
  426. **master** branch (or branch off of it).
  427. #. Write a test which shows that the bug was fixed or that the feature works as
  428. expected.
  429. #. Make the docs better (or more detailed, or more easier to read, or ...)
  430. .. _`the repository`: https://github.com/jd/tenacity