The two functions you're referencing — retry_if_not_exception_type and retry_unless_exception_type — are retry condition functions, often used with libraries like Tenacity, a popular Python library for retrying operations.
Both functions dictate when a retry should happen based on the type of exception raised, but they behave in opposite ways.
🔁 retry_if_not_exception_type
This retries if the exception is not of a given type.
✅ Meaning:
- If the raised exception is NOT the specified type (or types), the action will be retried.
- If the raised exception IS the specified type, no retry will happen.
✅ Use When:
You want to stop retrying for specific expected exceptions but retry all others.
🧠 Think of it like:
"Retry unless it's a value error."
🧪 Example:
from tenacity import retry, retry_if_not_exception_type
@retry(retry=retry_if_not_exception_type(ValueError))
def do_something():
...
do_something will not be retried if it raises a ValueError.
- It will retry for any other exception, like
TypeError, IOError, etc.
🔁 retry_unless_exception_type
This retries unless the exception is of the given type.
✅ Meaning:
- If the exception IS the specified type, it will retry.
- If the exception is NOT that type, it won’t retry.
✅ Use When:
You want to retry only specific exception types, and let all others fail immediately.
🧠 Think of it like:
"Retry only if it's a value error."
🧪 Example:
from tenacity import retry, retry_unless_exception_type
@retry(retry=retry_unless_exception_type(ValueError))
def do_something():
...
do_something will retry only if it raises a ValueError.
- It won't retry on
TypeError, IOError, etc.
🔁 Summary Table:
| Function | Retry When... | Don't Retry When... |
|---|
retry_if_not_exception_type | The exception is not of the given type | The exception is the given type |
retry_unless_exception_type | The exception is the given type | The exception is not the given type |
Let me know if you want code demos or more use cases!