Programming with Python · free preview

Type Hints and the Wider Ecosystem

Annotate functions and collections with type hints, understand what they do and do not enforce, and get oriented in pip, virtual environments, and where to go next.

1. Overview

Overview

2. Annotating Functions

Annotating Functions

3. Types for Collections

Types for Collections

4. Hints Are Documentation, Not Enforcement

Hints Are Documentation, Not Enforcement

5. Beyond the Browser

Beyond the Browser

6. Add the Hints

Add the Hints

7. Does It Stop?

Does It Stop?

8. Separate static and runtime checks

For def label(value: int) -> str: return value * "*" called as label(2.5), what happens?

9. Trace annotations, a runtime call, and a static-check scenario

Follow a complete example and separate runtime behavior from checkable documentation.

Example. Trace annotations, a runtime call, and a static-check scenario

Problem. Follow a complete example and separate runtime behavior from checkable documentation.

Correct solution.

Step 1, define annotated functions.

python
def to_celsius(fahrenheit: float) -> float:
 return (fahrenheit - 32) * 5 / 9

def find_id(records: dict[str, int], name: str) -> int | None:
 return records.get(name)

Step 2, call to_celsius and inspect annotations.

python
print(round(to_celsius(98.6), 1))
print(to_celsius.__annotations__)

Output.```output 37.0 {'fahrenheit': <class 'float'>, 'return': <class 'float'>}

code

Reasoning, the annotation metadata is stored on the function, and the call still executes the same body.

Step 3, show non-enforcement.

```python
def double(value: int) -> int:
 return value * 2

print(double('ha'))
print(double(2.5))

Output.```output haha 5.0

code

Reasoning, Python does not validate arguments against `int`. The first call succeeds because string repetition makes sense; the second succeeds because floats can be doubled. A static checker such as mypy would flag both calls before the program runs.

Step 4, use a collection annotation.

```python
records = {'Alice': 1, 'Bob': 2}
print(find_id(records, 'Bob'))
print(find_id(records, 'Carol'))

Output.``output 2 None ``

Reasoning,dict[str, int] documents the mapping and int | None documents that .get() may return an absent key as None.

关键提醒。

Annotations are documentation and tooling input; they are stored metadata, not runtime enforcement.

10. Retrieval practice

Use this new input without looking back, a helper is declared def label(value: int) -> str: return value * '*'. Predict the exact runtime output of print(label(3)), say why the annotation does not stop label(2.5), and name what reports that mismatch before running.

Give the exact output, the non-enforcement reason, and the checker name.

11. Mastery check

Apply type hints to a new signature, complete def average_temperature(readings: list[float], unit: str) -> float so it raises ValueError when unit is not 'c' or 'f', then state the exact annotation, the exact call average_temperature([36.6, 37.0], 'c') result, and why annotations alone do not reject that good call.

Give the completed signature, exact runtime result, and the annotation boundary.

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free