Summary - Type hints
- Python course
- Advanced
- Lesson 12/83
- 5 min
Combine Optional, Callable and TypeVar to write a type-safe function.
Summary - Type hints
This group covered the core tools of type hints. Basic types (int, str) document signatures; Optional adds the None possibility, Union combines several types.
List and Dict declare container types; Callable declares function parameters, TypeVar declares generic functions that preserve types.
The final task combines Optional and List: you'll write a function that finds an item in a list and returns Optional[str].
Practice pick function with List and Optional
Write pick(items: List[str], i: int) -> Optional[str]. If 0 <= i < len(items) return items[i]; otherwise return None. Import List and Optional from typing. Call print(pick(["a", "b"], 1)) and print(pick(["a", "b"], 5)).
Starter code
# import List and Optional from typing
# pick(items: List[str], i: int) -> Optional[str]
# if i is a valid index return the item, else None
# print the result of pick(["a", "b"], 1) and pick(["a", "b"], 5)Sample solution
from typing import List, Optional
def pick(items: List[str], i: int) -> Optional[str]:
if 0 <= i < len(items):
return items[i]
return None
print(pick(["a", "b"], 1))
print(pick(["a", "b"], 5))Expected output
b None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 A function may return either a string or None; which type do you use?
- Union[int, str]
- List[str]
- Callable[[int], int]
- Optional[str] Correct answer
Explanation: Optional[str] accepts str or None; it fits this scenario exactly.
2 List and Optional combined
from typing import List, Optional
def pick(items: List[str], i: int) -> ____[str]:
if 0 <= i < len(items):
return items[i]
return None
from typing import List, Optional
def pick(items: List[str], i: int) -> Optional[str]:
if 0 <= i < len(items):
return items[i]
return None
Explanation: Optional[str] declares that a string or None can be returned.
3 Match the group concepts
| Term | Meaning |
|---|---|
Optional[str] |
str or None |
List[int] |
List of integers |
Callable[[int], int] |
Takes int, returns int |
TypeVar("T") |
Generic type variable |