How to Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
Python code
28 linesdef divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, result = divide(10, 2)
print(f"Success: {success}, Result: {result}")
# Failure case
success, result = divide(5, 0)
print(f"Success: {success}, Result: {result}")
# Practical usage pattern
results = [
divide(20, 4),
divide(7, 0),
divide(15, 3)
]
for ok, value in results:
if ok:
print(f"Operation succeeded: {value}")
else:
print(f"Operation failed: {value}")
Output
Success: True, Result: 5.0
Success: False, Result: Error: Division by zero
Operation succeeded: 5.0
Operation failed: Error: Division by zero
Operation succeeded: 5.0
How it works
This pattern returns a tuple where the first element is a boolean flag indicating success, and the second is either the computed value or an error description. By checking the flag with if ok:, the caller avoids exceptions and handles failures inline with explicit control flow. Type hints like tuple[bool, float | str] document the contract clearly for other developers. It is a lightweight alternative to exceptions when errors are expected and need to be handled immediately.
Common mistakes
- Forgetting to unpack both tuple elements with `success, result = func()`
- Assuming the value slot always holds a number, even on failure
- Not checking the success flag before using the result value
Variations
- Use a namedtuple or dataclass like `Success(value)` / `Failure(message)` for clearer semantics
- Use exceptions with `raise ValueError` for truly exceptional cases
Real-world use cases
- Validating user input in a CLI tool, returning either a parsed value or a friendly error prompt.
- Parsing a config file entry, reporting a key-specific error message without aborting the whole load.
- Returning a result from a batch worker that skips invalid rows and logs per-record errors.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.