Type Hints and Function Contracts
The Development of Python Type Hints
BOTIE
Static analysis follows the program before executing its normal work. Runtime validation inspects values that actually arrive. These are different tasks: a checker can flag a known string passed to a numerical function, while an external response still needs a boundary that checks its contents.
Sources for this history
Why Did a Temperature Arrive as Text?
The greenhouse code expects a number, but a JSON record contains the string "21". A reader can see the difference when it is written out. A function signature with no annotations leaves that expectation hidden until the calculation runs.
We can state the intended types beside the parameters and return value. These are type hints. They help readers and analysis tools follow a program, but writing float beside a parameter does not turn incoming text into a temperature or validate it.
This construction checks values while it runs. It does not execute a static type checker. The deliberate policy here skips unusable values; a later lesson will require rejecting an entire invalid batch.
Step 1 of 1
Separate a declaration from an observed value
The signature describes an agreement; the boundary inspects actual incoming data.
| Item | What it says or contains | What establishes acceptance |
|---|---|---|
| parameter hint | temperature_c: float | a static expectation |
| first record | temperature_c is 21 | runtime numerical check |
| second record | temperature_c is "21" | explicit parsing or rejection policy |
parameter hint
- What it says or contains
- temperature_c: float
- What establishes acceptance
- a static expectation
first record
- What it says or contains
- temperature_c is 21
- What establishes acceptance
- runtime numerical check
second record
- What it says or contains
- temperature_c is "21"
- What establishes acceptance
- explicit parsing or rejection policy
Read an annotated signature
The check decides which incoming values may enter the numerical calculation. The type hint still describes that calculation to readers and static checking tools.
Check the Values Entering the Converter
The temperature converter expects numbers. A file can still send text such as "20", or a missing value, even when the Python function has a list[float] type hint. The hint explains what the function expects; it does not check the file.
BOTIE
Fahrenheit conversions of numerical readings
- 032
- 168
Follow the operations
1. Incoming Celsius values
- 00
- 120
2. Keep numerical readings
- 00
- 120
3. Celsius-to-Fahrenheit multiplier
1.8
4. Multiply
- 00
- 136
5. Fahrenheit offset
32
6. Add
- 032
- 168
7. Result
- 032
- 168
This construction checks values while it runs. It does not execute a static type checker. The deliberate policy here skips unusable values; a later lesson will require rejecting an entire invalid batch.
1. Read an annotated signature
A parameter annotation follows a colon. The return annotation follows an arrow after the parameters. These names describe intended values; they do not add a conversion step to the function body.
A type hint should describe the interface that callers can actually use.
Describe one input and one result
The function states a numerical interface and still performs ordinary Python arithmetic.
def double_reading(value: float) -> float:
return value * 2
print(double_reading(2.5))
print(double_reading("x"))5.0
xxThe string call runs because Python does not enforce the annotation. Its result violates the intended interface, which is a problem a static checker can identify.
2. Describe collections and named structures
list[float] describes a list of numerical entries. dict[str, float] describes a mapping from text keys to numerical values. A nested structure needs its own explanation of what each level means.
A type hint cannot express every agreement we care about. A list of floats could be empty, use the wrong unit or contain an infinite value. The signature and docstring work together with runtime checks.
Record names and units remain necessary even when the container type is precise.
Annotate a returned list
The input mapping identifies greenhouse names, and the returned list follows the requested name order.
def readings_in_order(by_house: dict[str, float], names: list[str]) -> list[float]:
return [by_house[name] for name in names]
print(readings_in_order({"north": 12.0, "south": 18.0}, ["south", "north"]))[18.0, 12.0]The annotation documents container roles. A missing name would still require a stated error or fallback policy.
Check yourself
Questions on Parts 1 to 2
Question 1 of 2
What does the annotation itself do?
Question data
def double_reading(value: float) -> float:
return value * 2
A caller passes "x".3. Use static analysis for known incompatibilities
A static type checker examines source code and its declared interfaces without running the program as a user would. Tools such as mypy and Pyright can identify many incompatible arguments or return values before a deployment.
They are not a proof of complete correctness. Unannotated code, deliberately broad types and external values can leave gaps. This site runs the Python programs themselves; the coding runner is not a bundled mypy or Pyright process.
Run the appropriate checker in a real project alongside tests. Passing one tool does not establish the input units or business rules.
4. Validate data that crosses the boundary
A JSON field can contain a string, a boolean or a missing value. State whether the boundary parses a particular format or rejects it. Do not let an annotation silently stand in for that decision.
Python booleans are related to integers in its type hierarchy. When this measurement contract rejects booleans, an explicit type check can distinguish them from intended numerical readings. A separate finite-value check rejects NaN and infinity.
The workshop checks incoming values before converting temperatures. That check runs when the construction runs; it is separate from a Python type hint.
5. Keep annotations useful as the code changes
Annotate public boundaries and update their hints when the interface changes. Let a clear type describe one responsibility rather than hiding unrelated records behind a broad Any everywhere.
Use typing.get_type_hints when a tool needs resolved annotation values. Annotation evaluation differs between Python versions, so inspecting a raw annotation representation is not a substitute for understanding the declared interface.
The exercises test the annotated contract and the actual runtime behavior separately.
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
Which boundary decision is needed?
Question data
A JSON field contains true. The measurement contract excludes booleans.Try it with Botie
Build with Botie
Write and run Python