Complex Types: List, Dict, Optional, Union
Use typing module generics and Optional/Union correctly.
typing Module Overview
Before Python 3.9, generic types like List, Dict, Tuple came from typing. Since 3.9 you can use the built-in types directly.
from typing import List, Dict, Tuple, Optional, Union
# Python 3.9+: use list[int], dict[str,int] directly
# Python 3.8-: use typing.List[int], typing.Dict[str,int]List and Sequence
Use list[T] for mutable sequences and Sequence[T] when accepting any ordered sequence (list, tuple, str).
from typing import Sequence
def total(nums: list[int]) -> int:
return sum(nums)
def first(items: Sequence[str]) -> str:
return items[0] # works with list, tuple, strAll lessons in this course
- Basic Type Annotations
- Complex Types: List, Dict, Optional, Union
- TypeVar, Generic Classes, and Protocol
- Running mypy and Fixing Type Errors