Python Hunter
Python Hunter

Reputation: 2146

Python tenacity: How to retry if exception is NOT of a certain type?

How to retry a function if the exception is NOT of a certain type using Python's tenacity?

retry_if_exception_type will retry if there is risen an exception of a certain type. not does not seems to work placed before the method nor before its arguments.

retry_unless_exception_type, on the other side, loops forever, even if there is not risen error, until there is risen error of a certain type.

Upvotes: 5

Views: 12310

Answers (4)

congusbongus
congusbongus

Reputation: 14622

retry_if_not_exception_type is available since version 8.0.0

Retries except an exception has been raised of one or more types.

So if you use retry_if_not_exception_type((ValueError, OSError)), it will retry for any exception, except ValueError or OSError.

Upvotes: 4

mikenerone
mikenerone

Reputation: 2045

Breaking it down a bit, what you want is to retry if:

  • an exception is raised
  • (and) unless the exception is of a certain type

So write that:

retry_if_exception_type() & retry_unless_exception_type(ErrorClassToNotRetryOn)

Upvotes: 0

Jevgeni M.
Jevgeni M.

Reputation: 61

I had to create my own class for that:

class retry_if_exception_unless_type(retry_unless_exception_type):
    """Retries until successful outcome or until an exception is raised of one or more types."""

    def __call__(self, retry_state):
        # don't retry if no exception was raised
        if not retry_state.outcome.failed:
            return False
        return self.predicate(retry_state.outcome.exception())

Upvotes: 1

Ben Sachs
Ben Sachs

Reputation: 1

using retry_unless_exception_type() combined with stop_after_attempt() worked for me to accomplish this. the stop_after_attempt() prevents the infinite looping.

Upvotes: 0

Related Questions