Optional values (X | None, Optional[X])
`X | None` is a type hint that says: this value is either type X or None, meaning it may be missing.
Used in 23 lessons of the course, from 00.06.
An optional value is one that may or may not be there. In Python, "not there" is represented by None.
To say it in a type hint you write str | None: read it as "a str or None". It is the same as Optional[str], which comes from the typing module. The | form is shorter and is the one you'll see today.
The course uses it like this: def fetch_text(url: str) -> str | None:. The function returns text if it got some, or None if not. The hint warns the caller to check the result before using it.
Note: Optional does not mean "argument with a default value". It only describes the type. If you want the parameter to be omittable, you must give it a default separately.
def first(words: list[str]) -> str | None:
return words[0] if words else None
Reach for it when: a function may have no result, or a value may be missing, and you want the hint to say so.
Examples
Common mistake
def find(name: str) -> str | None:
return None
result = find("x")
print(result.upper())Why: The hint warned the result could be None, and None has no str methods.
How to write it: Check first: if result is not None: and then use result.upper().
