Full answer
python
def total(prices: list[float], tax: float = 0.18) -> float:
return round(sum(prices) * (1 + tax), 2)
print(total([100.0, 50.0]))
print(total.__annotations__)
try:
print(total(["100"]))
except TypeError as e:
print("TypeError at runtime:", e)
from typing import TypedDict
class User(TypedDict):
name: str
age: int
u: User = {"name": "Asha", "age": "twenty"}
print(u)Output:
text
177.0
{'prices': list[float], 'tax': <class 'float'>, 'return': <class 'float'>}
TypeError at runtime: unsupported operand type(s) for +: 'int' and 'str'
{'name': 'Asha', 'age': 'twenty'}Annotations are stored in __annotations__ and otherwise ignored when the code runs. Passing a list of strings fails only because sum cannot add strings, not because of the hint. The TypedDict with a wrong age type is accepted at runtime; a type checker would report it. Modern syntax uses built-in generics such as list[float] and unions like int | None. Adding hints to function signatures first gives most of the benefit in a codebase.
python
def total(prices: list[float], tax: float = 0.18) -> float:
return round(sum(prices) * (1 + tax), 2)
print(total([100.0, 50.0]))
print(total.__annotations__)
try:
print(total(["100"]))
except TypeError as e:
print("TypeError at runtime:", e)
from typing import TypedDict
class User(TypedDict):
name: str
age: int
u: User = {"name": "Asha", "age": "twenty"}
print(u)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Hints are not enforced at runtime
- Type checkers use them statically
- Stored in __annotations__
- Use list[int] and X | None syntax
- Pydantic validates explicitly
Common mistakes
- Expecting hints to reject wrong types
- Over-annotating local variables
Follow-ups
- What is the difference between mypy and Pydantic validation?
- What are Protocols?
Tips
- Separate static checking from runtime