AlgoMaster Logo

Optional & Union

Last Updated: May 22, 2026

Medium Priority
9 min read

Many real functions don't return one neat type. A lookup might find a product or come back empty. A field might hold a customer ID or be missing. A parsed value might be an int when the input was numeric and a string otherwise. Python's type system handles all of this with two related constructs: Optional[X] for "X or None", and Union[A, B] for "one of several types". Since Python 3.10 (PEP 604), the | operator collapses both into a shorter syntax. This lesson covers every flavor, how to handle these types safely in code, and the patterns that keep annotations honest.

Premium Content

Subscribe to unlock full access to this content and more premium articles.