Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 37 / 101

Make the contract visible.

Describe expected values for readers and static checkers without confusing hints with validation.

ADVANCED LAB
BY NAVAN SAMI◷ 9 MIN READPYTHON 3

01 The idea

Type hints document an interface in a form that tooling can inspect. A list[int] annotation says the intended elements are integers; it does not automatically reject an incorrect caller at runtime. Use a static checker during development and runtime validation at external boundaries. Together they answer different questions: does the code fit the declared model, and is this incoming value actually acceptable?

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

type_hints.py
def average(values: list[float]) -> float:
    if not values:
        raise ValueError("Need at least one value")
    return sum(values) / len(values)

print(average([10.0, 20.0, 30.0]))
↳ EXPECTED OUTPUT
20.0

03 Under the hood

  1. 1

    Parameter and return annotations tell the reader what shapes are expected. The calculation still uses ordinary Python operations.

  2. 2

    The empty-input guard is runtime behaviour, not a consequence of the annotation. It prevents a division by zero and provides an intentional error message.

  3. 3

    Use str | None for an optional string and choose a clear strategy for the None branch. Prefer specific types over annotating everything as Any, which weakens static feedback.

04 Your turn, builder

A SMALL MISSION

Write a typed function that returns the longest word, returning None for an empty list.

Reveal one possible solution +
one_possible_solution.py
def longest(words: list[str]) -> str | None:
    return max(words, key=len) if words else None

print(longest(["code", "possibility"]))
print(longest([]))

05 Check your signal

QUICK SIGNAL CHECK

Do annotations alone reject an incorrect argument at runtime?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.