Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
features:
- Add ``retry_if_not_exception_type()`` that allows to retry if a raised exception doesn't match given exceptions.
1 change: 1 addition & 0 deletions tenacity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from .retry import retry_any # noqa
from .retry import retry_if_exception # noqa
from .retry import retry_if_exception_type # noqa
from .retry import retry_if_not_exception_type # noqa
from .retry import retry_if_not_result # noqa
from .retry import retry_if_result # noqa
from .retry import retry_never # noqa
Expand Down
10 changes: 10 additions & 0 deletions tenacity/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ def __init__(self, exception_types=Exception):
)


class retry_if_not_exception_type(retry_if_exception):
"""Retries except an exception has been raised of one or more types."""

def __init__(self, exception_types=Exception):
self.exception_types = exception_types
super(retry_if_not_exception_type, self).__init__(
lambda e: not isinstance(e, exception_types)
)


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

Expand Down
17 changes: 17 additions & 0 deletions tenacity/tests/test_tenacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,11 @@ def _retryable_test_with_exception_type_io(thing):
return thing.go()


@retry(retry=tenacity.retry_if_not_exception_type(IOError))
def _retryable_test_if_not_exception_type_io(thing):
return thing.go()


@retry(
stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_exception_type(IOError)
)
Expand Down Expand Up @@ -921,6 +926,18 @@ def test_retry_if_exception_of_type(self):
self.assertTrue(isinstance(n, NameError))
print(n)

def test_retry_except_exception_of_type(self):
self.assertTrue(
_retryable_test_if_not_exception_type_io(NoNameErrorAfterCount(5))
)

try:
_retryable_test_if_not_exception_type_io(NoIOErrorAfterCount(5))
self.fail("Expected IOError")
except IOError as err:
self.assertTrue(isinstance(err, IOError))
print(err)

def test_retry_until_exception_of_type_attempt_number(self):
try:
self.assertTrue(
Expand Down