Interview Prep/Python for DevOps/Language essentials & functions

Explain `Optional`, union syntax, and `None` handling in type hints.

IntermediateConceptLanguage essentials & functions
Answer

Optional[str] means str | None (the | syntax is available from 3.10). It does not mean "optional argument"; it means the value may be None.

def find_instance(name: str) -> dict[str, Any] | None: ...

inst = find_instance("web-1")
inst["InstanceId"]          # mypy: Value of type "dict | None" is not indexable
if inst is not None:
    inst["InstanceId"]      # ok, narrowed

This forces you to handle the "not found" path, which is exactly the bug that pages someone at 3 AM.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions