Python

Lesson 08

Type hints at boundaries

Add type hints where data enters or leaves a module so assumptions are visible to tools and reviewers.

Good Code

review_input.py
from dataclasses import dataclass
from typing import Mapping


@dataclass(frozen=True)
class ReviewInput:
    title: str
    author_id: int


def parse_review_input(payload: Mapping[str, object]) -> ReviewInput:
    return ReviewInput(
        title=str(payload["title"]),
        author_id=int(payload["author_id"]),
    )

Bad Code

review_input.py
def parse_review_input(payload):
    return {
        "title": payload["title"],
        "author_id": payload["author_id"],
    }

Review Notes

What to review

Good Code

The good version tells callers what kind of payload is accepted and returns a named object with typed fields.

Bad Code

The bad version accepts and returns anything. Reviewers cannot see whether author_id should be a string, number, or optional value.

Takeaways

  • Type hints are most valuable at module boundaries, not as decoration on obvious local variables.