Python course / Working Python
Type hints
Say what your functions take and hand back, and read what a type checker tells you. Python stores hints and never checks them, which is the first thing most people get wrong about them.
- function hints
- collections
- X | None
- unions
- Any
- Protocols
- TypedDict
- type checkers
Runs in your browser. Start straight away; create an account when you want your progress kept.
def total(prices: list[float], discount: float | None = None) -> float:
amount = sum(prices)
if discount is not None:
amount -= discount
return amount
print(total([3.5, 2.25]))
print(total([3.5, 2.25], discount=1.0))
print("hints:", total.__annotations__)
5.75
4.75
hints: {'prices': list[float], 'discount': float | None, 'return': <class 'float'>}
What you will learn
- Know that Python stores type hints and never checks them.
- Write hints for parameters, defaults and the return value, including a function that returns nothing.
- Say what a list, dictionary, set or tuple holds, in the form current Python uses.
- Hint a value that can be missing, and handle the missing case without mistaking it for zero.
- Hint "anything with this method" without making every class inherit from one parent.
- Know what a type checker does, what it cannot see, and how to read what it says.
The lessons in this module
- What a hint is, and what it is not
- Hinting a function
- Reading hints back
- Hinting variables and attributes
- Hinting collections
- Maybe nothing: X | None
- Unions, and when they keep growing
- Any
- Hinting your own classes
- Hinting functions: Callable
- Protocols: hinting what an object can do
- TypedDict: hinting a dictionary's shape
- Type checkers
- When hints earn their place
- Hinting a module, and what it finds
- Module review: the price list
Ready when you are
Previous: Comprehensions. Next: Standard library tour. All modules are on the course page.