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.

Easy Python 3.10+ Aug 9, 2026 Errors & debugging 11 views 0 copies

Python code

28 lines
Python 3.10+
def 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

stdout
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

  1. Use a namedtuple or dataclass like `Success(value)` / `Failure(message)` for clearer semantics
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.