Separate Type Annotations from Runtime Validation
Core idea
An annotation describes an expected type to readers and static analysis tools: def f(x: int) -> str declares an integer parameter and string result. Python does not automatically check these contracts when a call executes. Use annotations to express design intent and explicit validation at boundaries that accept unknown data.
from typing import get_type_hintsdef label(count: int) -> str: return f'Items: {count}'print(label(4))print(get_type_hints(label)['count'] is int)The annotation is metadata; the body formats a string. Inspect hints only on trusted definitions because resolution may evaluate expressions.
Intentionally mismatched call
def twice(n: int) -> int: return n + n# Deliberate type mismatch for a runtime demonstrationprint(twice('ha'))A checker should reject this call, but string addition succeeds at runtime.
Common mistake
Type hints are not a validation or security layer. Validate external input with appropriate checks, and do not assume an annotated return value has been checked.
Practice
Write a function accepting object; return a label only after isinstance(value, str). Explain which check actually runs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Annotations and runtime boundaries
Check your understanding of annotations and runtime boundaries.
What is printed?
def f(x: int) -> int: return xprint(f('3'))What is printed?
def f(x: int) -> str: return str(x)print(f.__annotations__['return'] is str)What automatically rejects an annotated argument of the wrong type?
Which is useful for validating unknown external values?