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.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner