From 7718ec1a59e70aeea12398a4ca1335ff22142799 Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Tue, 24 Feb 2026 08:42:22 +0100 Subject: [PATCH] fix: initialize delay_since_first_attempt in statistics on begin() Closes #421 Co-Authored-By: Claude Opus 4.6 Change-Id: I104d68d8dbfe41282632b8183c267aa88d682be3 --- tenacity/__init__.py | 1 + tests/test_tenacity.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/tenacity/__init__.py b/tenacity/__init__.py index c43475c4..079740f6 100644 --- a/tenacity/__init__.py +++ b/tenacity/__init__.py @@ -354,6 +354,7 @@ def begin(self) -> None: self.statistics["start_time"] = time.monotonic() self.statistics["attempt_number"] = 1 self.statistics["idle_for"] = 0 + self.statistics["delay_since_first_attempt"] = 0 def _add_action_func(self, fn: t.Callable[..., t.Any]) -> None: self.iter_state.actions.append(fn) diff --git a/tests/test_tenacity.py b/tests/test_tenacity.py index 017e6831..0645a835 100644 --- a/tests/test_tenacity.py +++ b/tests/test_tenacity.py @@ -1354,6 +1354,23 @@ def test_retry_function_attributes(self) -> None: self.fail("RetryError should have been raised after 1 attempt") +class TestStatisticsKeys: + def test_delay_since_first_attempt_available_on_first_attempt(self) -> None: + """delay_since_first_attempt should be in statistics from the start.""" + + @retry( + stop=tenacity.stop_after_attempt(3), + retry=tenacity.retry_if_result(lambda x: x is None), + ) + def succeeds_first_try() -> bool: + assert "delay_since_first_attempt" in succeeds_first_try.statistics + assert succeeds_first_try.statistics["delay_since_first_attempt"] == 0 + return True + + succeeds_first_try() + assert succeeds_first_try.statistics["delay_since_first_attempt"] == 0 + + class TestRetryWith: def test_redefine_wait(self) -> None: start = current_time_ms()