Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion tenacity/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,12 @@ def __call__(self, retry_state: "RetryCallState") -> bool:
raise RuntimeError("__call__ called before outcome was set")

if retry_state.outcome.failed:
seen: set[int] = set()
exc = retry_state.outcome.exception()
while exc is not None:
while exc is not None and id(exc) not in seen:
if isinstance(exc.__cause__, self.exception_cause_types):
return True
seen.add(id(exc))
exc = exc.__cause__

return False
Expand Down
25 changes: 25 additions & 0 deletions tests/test_tenacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -1441,6 +1441,31 @@ def test_retry_if_exception_cause_type(self) -> None:
except NameError:
pass

def test_retry_if_exception_cause_type_with_cause_cycle(self) -> None:
# A cyclic __cause__ chain (e.g. ``raise e from e``) must not hang the
# cause scan; the predicate should give up once the chain repeats.
def _raise_self_caused() -> None:
try:
raise ValueError("inner")
except ValueError as e:
raise e from e

def _raise_two_node_cycle() -> None:
first = KeyError("first")
second = OSError("second")
first.__cause__ = second
second.__cause__ = first
raise first

for raiser in (_raise_self_caused, _raise_two_node_cycle):
r = Retrying(
retry=tenacity.retry_if_exception_cause_type(NameError),
stop=tenacity.stop_after_attempt(2),
reraise=True,
)
with self.assertRaises((ValueError, KeyError)):
r(raiser)

def test_retry_preserves_argument_defaults(self) -> None:
def function_with_defaults(a: int = 1) -> int:
return a
Expand Down
Loading