Outcome

1.3.0.post0 · active · verified Sat Mar 28

Outcome is a Python library extracted from the Trio project, designed to capture the outcome (return value or raised exception) of both synchronous and asynchronous Python function calls. It provides a standardized way to pass around results that might otherwise be exceptions, facilitating structured error handling. The current version is 1.3.0.post0, with releases occurring periodically to add features and address issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `outcome.capture` for synchronous functions and `outcome.acapture` for asynchronous functions, handling both successful returns and raised exceptions. It also illustrates the `AlreadyUsedError` which is raised if an `Outcome` object's value or error is attempted to be accessed more than once.

import outcome
import asyncio

def successful_function():
    return "Success!"

def failing_function():
    raise ValueError("Something went wrong!")

async def async_successful_function():
    await asyncio.sleep(0.01)
    return "Async Success!"

async def async_failing_function():
    await asyncio.sleep(0.01)
    raise RuntimeError("Async operation failed!
")

# Example 1: Synchronous capture
sync_success_outcome = outcome.capture(successful_function)
print(f"Sync Success: {sync_success_outcome.unwrap()}")

sync_failure_outcome = outcome.capture(failing_function)
try:
    sync_failure_outcome.unwrap()
except ValueError as e:
    print(f"Sync Failure caught: {e}")

# Example 2: Asynchronous capture
async def main():
    async_success_outcome = await outcome.acapture(async_successful_function)
    print(f"Async Success: {async_success_outcome.unwrap()}")

    async_failure_outcome = await outcome.acapture(async_failing_function)
    try:
        async_failure_outcome.unwrap()
    except RuntimeError as e:
        print(f"Async Failure caught: {e}")

    # Demonstrating AlreadyUsedError (Outcome objects can only be unwrapped once)
    try:
        print(sync_success_outcome.unwrap()) 
    except outcome.AlreadyUsedError as e:
        print(f"Caught expected error: {e}")

asyncio.run(main())

view raw JSON →