DevPath
Mid lesson · 12 min

Keep Python type hints honest

Use hints for readers and tools, and validate external values at runtime.

Hints describe intent

A type annotation does not prevent a caller from passing malformed data at runtime. It helps static analysis and documents what trusted code should exchange. At JSON, CSV, environment, and database boundaries, inspect and normalize actual values before constructing typed domain objects.

Narrow unknown values

A payload may be a list when the endpoint expects a mapping, or a boolean when an integer is expected. Check the container and fields explicitly. Keep optional data as optional until the domain rule supplies a genuine default; inventing zero can hide missing information.

def parse_limit(value: object) -> int:
    if type(value) is not int or value < 1:
        raise ValueError('limit must be a positive integer')
    return value

Test the boundary, not the hint

Pass a valid integer, a numeric string, None, a float, and True. Verify the promised error for each invalid case. A typed function can still fail on external input if validation is skipped, so tests should enter through the same boundary as real data.

Check your understanding

Why use `type(value) is int` in this parser instead of `isinstance(value, int)`?

Show explanation

In Python, bool is a subclass of int; the exact-type check rejects True and False when a real integer is required.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Stream a large file without loading it

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.