Practice: Type Hints
Q1. Hint a function
Write a function add(a, b) with int hints for both parameters and the return value, then print add(2, 3).
Goal: Annotate a function
Q2. List of strings
Write shout(words) that takes list[str] and returns a list of uppercase words. Print shout(['hi', 'yo']).
Goal: Hint collections
Q3. Optional lookup
Write get_price(prices, item) hinted as dict[str, float] and str returning float | None. Print the result for 'tea' in {'tea': 2.5} and for 'milk'.
Goal: Optional values
Q4. Tuple return
Write min_max(nums: list[int]) returning tuple[int, int]. Print min_max([4, 9, 1, 7]).
Goal: Tuple hints
Q5. Show the annotations
Define def f(x: int, y: str = 'a') -> bool and print f.__annotations__ (return True from the body).
Goal: Inspect annotations
Q6. Generic last item
Write a generic last(items: list[T]) -> T using TypeVar and print last([1, 2, 3]) and last(['x', 'y']).
Goal: Generics
Q7. Type alias
Create an alias Pair = tuple[int, int] and a function swap(p: Pair) -> Pair. Print swap((1, 2)).
Goal: Type aliases
Q8. Wrong type allowed
What does this print?
def twice(n: int) -> int:
return n * 2
print(twice('ha'))Goal: Hints are not enforced
Q9. Annotations dict
What does this print?
def g(a: str) -> None:
pass
print(g.__annotations__)Goal: Read __annotations__
Q10. Variable without value
What does this print?
x: int
print('start')
try:
print(x)
except NameError:
print('no value')Goal: Variable annotations
Q11. Union result
What does this print?
def show(v: int | str) -> str:
return str(v) + '!'
print(show(7))
print(show('go'))Goal: Union types
Q12. Module annotations
What does this print?
count: int = 5
name: str = 'Lee'
print(__annotations__)Goal: Variable annotations
Q13. Fix the Optional use
This code crashes when the key is missing. Fix it so it prints 0 for a missing name.
def length(d: dict[str, str], k: str) -> int:
return len(d.get(k))
print(length({'a': 'xyz'}, 'b'))Goal: Handle Optional
Q14. Fix the list hint
This code fails with a TypeError when defining the function. Fix the hint so it prints 6.
def total(nums: list(int)) -> int:
return sum(nums)
print(total([1, 2, 3]))Goal: Fix generic syntax
Q15. Hints at run time
Does Python raise an error if you call a function hinted with int using a string? Explain.
Goal: Enforcement of hints
Q16. Why TypeVar
Why is def first(items: list[T]) -> T better than def first(items: list) -> Any?
Goal: Understand generics
Q17. Document an API
You write a function that reads a user dictionary and returns the email or None. Write a hinted version and print the result for {'email': 'a@b.com'}.
Goal: Use hints to document