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
16 changes: 15 additions & 1 deletion tenacity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,15 @@ def __iter__(self) -> t.Generator[AttemptManager, None, None]:
self.begin()

retry_state = RetryCallState(self, fn=None, args=(), kwargs={})
# When used as a context manager without an explicit name=, infer the
# caller's qualified name from the frame that called next() on this
# generator (i.e. the for-loop body in user code).
if self._name is None:
_frame = sys._getframe(1)
retry_state._inferred_name = (
getattr(_frame.f_code, "co_qualname", None)
or _frame.f_code.co_name
)
while True:
do = self.iter(retry_state=retry_state)
if isinstance(do, DoAttempt):
Expand Down Expand Up @@ -603,10 +612,15 @@ def get_fn_name(self) -> str:

Returns the fully-qualified name of the wrapped function when used as a
decorator, the ``name`` passed to the retrying object when used as a
context manager, or ``"<unknown>"`` if neither is available.
context manager, the inferred caller name when used as a context manager
without an explicit ``name``, or ``"<unknown>"`` if none is available.
"""
if self.fn is not None:
return _utils.get_callback_name(self.fn)
# Inferred from the caller's frame in __iter__ (context-manager usage)
inferred: str | None = getattr(self, "_inferred_name", None)
if inferred is not None:
return inferred
return str(self.retry_object)

@property
Expand Down
36 changes: 36 additions & 0 deletions tests/test_tenacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,42 @@ def test_logging_uses_name(self) -> None:
args = log.call_args[0]
assert "my_block" in args[1]

def test_logging_infers_caller_name(self) -> None:
"""before_log infers the enclosing function name when no name= is given (#511).

When Retrying is used as a context manager without an explicit name=
parameter, retry_state.fn is None. Before the fix, get_fn_name() would
fall back to str(retry_object) == "<unknown>". Now __iter__ captures
sys._getframe(1) — the for-loop frame — and stores co_qualname / co_name
as retry_state._inferred_name so that before_log() can log something
meaningful instead of '<unknown>'.
"""
import unittest.mock

log = unittest.mock.MagicMock()
logger = unittest.mock.MagicMock(log=log)

def my_retry_function() -> None:
with contextlib.suppress(Exception):
for attempt in Retrying(
before=tenacity.before_log(logger, logging.INFO),
stop=tenacity.stop_after_attempt(1),
):
with attempt:
raise ValueError("boom")

my_retry_function()

# before_log must have been called at least once
assert log.call_args is not None, "before_log was never called"
msg = log.call_args[0][1]
assert "<unknown>" not in msg, (
f"Expected an inferred caller name in the log message, got: {msg!r}"
)
assert "my_retry_function" in msg, (
f"Expected 'my_retry_function' in the log message, got: {msg!r}"
)


class TestStopConditions(unittest.TestCase):
def test_never_stop(self) -> None:
Expand Down
Loading