How to Use Optional Return in Python Instead of Raising Exceptions

A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 15 views 0 copies

Python code

29 lines
Python 3.9+
from typing import Optional


def find_user(users: dict, user_id: int) -> Optional[dict]:
    """
    Look up a user by ID. Returns the user dict if found,
    otherwise returns None instead of raising KeyError.
    """
    return users.get(user_id)


def main() -> None:
    users = {
        1: {"name": "Alice", "email": "alice@example.com"},
        2: {"name": "Bob", "email": "bob@example.com"},
    }

    user = find_user(users, 1)
    print(f"Found user: {user}")

    missing = find_user(users, 99)
    print(f"Missing user: {missing}")

    if missing is None:
        print("No exception raised — graceful handling with Optional return.")


if __name__ == "__main__":
    main()

Output

stdout
Found user: {'name': 'Alice', 'email': 'alice@example.com'}
Missing user: None
No exception raised — graceful handling with Optional return.

How it works

The function uses dict.get() instead of direct indexing, so a missing key returns None rather than raising KeyError. The Optional[dict] type hint tells readers and type checkers that the return may be None, making the contract explicit. This pattern avoids try/except blocks for expected missing data, keeping control flow simple. It works because dict.get() is a standard, safe way to access keys with a configurable default (None here). This design is especially useful when missing values are a normal, expected part of the domain.

Common mistakes

  • Returning None silently for truly exceptional cases where a failure should be loud
  • Forgetting to check for None at the call site, leading to AttributeError later
  • Using dict[key] directly in the function body, reintroducing KeyError

Variations

  1. Use `dict.get(key, default_value)` to return a custom fallback instead of None
  2. Use `match` statements (Python 3.10+) to pattern-match the Optional result

Real-world use cases

  • Looking up a user or configuration record in a database cache without crashing on cache misses.
  • Fetching an optional discount code or promo field from a product payload where absence means no discount.
  • Resolving session or feature-flag metadata where a missing key should silently default to off or unset.

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.