From f1c175975f52a2f54a38ed583f0677e16a7ccf0f Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Mon, 23 Feb 2026 18:08:23 +0100 Subject: [PATCH] docs: add common patterns section for recurring FAQ topics Add examples for two frequently asked usage patterns: - Running setup code between retries (before_sleep for reconnection) - Accessing the attempt number inside the function (iterator API) These address recurring questions from issues #298, #316, #344, #361. Co-Authored-By: Claude Opus 4.6 Change-Id: Ic4cea9f63db72a6f9cb47287597a8dacffdc8533 --- doc/source/index.rst | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/doc/source/index.rst b/doc/source/index.rst index bcb02bbb..2d1e9f8e 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -510,6 +510,52 @@ Here's an example with a custom ``before_sleep`` function: pass +Common Patterns +~~~~~~~~~~~~~~~ + +**Running setup code between retries** (e.g. reconnecting): + +.. testcode:: + + def reconnect(retry_state): + print("Reconnecting before next attempt...") + + @retry(stop=stop_after_attempt(3), before_sleep=reconnect) + def send_data(): + raise MyException("connection lost") + + try: + send_data() + except RetryError: + pass + +.. testoutput:: + :hide: + + ... + +The ``before_sleep`` callback runs after a failed attempt and before sleeping, +making it ideal for re-establishing connections, refreshing tokens, or any +other setup that needs to happen before the next attempt. + +**Accessing the attempt number inside the function** using the iterator API: + +.. testcode:: + + from tenacity import Retrying + + for attempt in Retrying(stop=stop_after_attempt(3)): + with attempt: + print(f"Attempt {attempt.retry_state.attempt_number}") + if attempt.retry_state.attempt_number < 3: + raise MyException("not yet") + +.. testoutput:: + :hide: + + ... + + Changing Arguments at Run Time ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~