tenacity icon indicating copy to clipboard operation
tenacity copied to clipboard

Unreachable code in `before_log` reached

Open zdebra opened this issue 11 months ago • 1 comments

Hello, I've reached code that is marked as unreachable in before_log function:

import logging

from tenacity import RetryError, Retrying, before_log

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)


def f():
    try:
        for attempt in Retrying(
            before=before_log(logger, logging.DEBUG),
        ):
            with attempt:
                raise Exception("hello")
    except RetryError as exc:
        exc.reraise()


f()

This code sample produces:

2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72232nd time calling it.
2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72233rd time calling it.
2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72234th time calling it.
2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72235th time calling it.
2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72236th time calling it.
2025-01-28 15:11:42,725 - DEBUG - Starting call to '<unknown>', this is the 72237th time calling it.

This is because retry_state.fn is probably not being set here.

Python 3.9.19 & tenacity 9.0.0.

zdebra avatar Jan 28 '25 14:01 zdebra

This comment "# NOTE(sileht): can't really happen, but we must please mypy" is outdated. retry_state.fn can be None in the case of using retry inside context manager. its the expected behaviour not a bug.

LotfiRafik avatar Feb 16 '25 17:02 LotfiRafik