
Code
Containers & Maybe-Values
Built-in collections put the type of their contents in square brackets:
names: list[str] = ["Reef", "Mill"]
stock: dict[str, int] = {"oil": 5}
point: tuple[int, int] = (3, 4)
tags: set[str] = {"urgent"}
Maybe a value, maybe None
Many functions return a result or None when there's nothing to
return. Write that with the | ("or") operator:
def find_key(keys: list[str], color: str) -> str | None:
for k in keys:
if color in k:
return k
return None
Older code writes the same thing as Optional[str] (from typing).
str | None and Optional[str] mean exactly the same.
Pip tip: When a function might return
None, a type checker reminds callers to check forNonebefore using the result. That catches one of the most common bugs in Python.
Assignment
Write both functions with full type hints:
find_island(islands: list[str], prefix: str) -> str | None: return the first island starting withprefix, orNone.tally(words: list[str]) -> dict[str, int]: count how many times each word appears.
Write both functions with full type hints:
find_island(islands: list[str], prefix: str) -> str | None: return the first island starting withprefix, orNone.tally(words: list[str]) -> dict[str, int]: count how many times each word appears.
main.py Python sleeping
Press Run to try your code, then Check to test it.