How to use Optional type hint in Python

Use the Optional type hint to indicate a parameter can be a string or None, with an example function that handles both cases.

Easy Python 3.10+ Aug 9, 2026 Testing & modern typing 11 views 0 copies

Python code

11 lines
Python 3.10+
from typing import Optional

def greet(name: Optional[str]) -> str:
    if name is None:
        return "Hello, anonymous!"
    else:
        return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet(None))

Output

stdout
Hello, Alice!
Hello, anonymous!

How it works

The Optional[str] type hint is equivalent to Union[str, None] and tells type checkers that a value may be a string or None. This example shows how to combine type hints with runtime checks to safely handle None. The if name is None: check narrows the type within the else branch, improving static analysis and preventing AttributeError when accessing string methods. Using type hints improves code clarity and enables tools like mypy to catch potential issues before runtime.

Common mistakes

  • Using `Optional[str]` without actually handling None, leading to runtime errors.
  • Confusing `Optional` with `Union` vs `Union[str, None]` — they are the same.
  • Using `if name:` instead of `if name is None:` which treats empty strings as falsy.
  • Forgetting that `Optional` is from `typing` and should be imported in older Python versions.

Variations

  1. Use `str | None` as a type hint in Python 3.10+ instead of `Optional[str]`.
  2. Use `Union[str, None]` from the `typing` module for compatibility with older Python.

Real-world use cases

  • Defining function parameters in APIs that accept optional user input, like a name in a greeting service.
  • Modeling fields in data classes that may be absent in database records, such as an optional middle initial.
  • Handling results from external calls that can return None, like a cache lookup that may miss.

Sponsored

Run this sample

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

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.