FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Books & courses

Why type your Python when the runtime ignores it

Patrick Viafore’s Robust Python helps you catch mistakes as you write them, but customer data still needs a guard of its own.

Cover of Robust Python: Write Clean and Maintainable Code
Robust Python: Write Clean and Maintainable Code · Patrick Viafore · Cover: Open Library
ShareLinkedInFacebookX

In brief

  • The book teaches you to use classes, enums and type hints so that errors surface while you are writing the code.
  • A type checker never sees the real data, so you need Pydantic at the point where customer data comes in.
  • Type the code that produces value first, then protect the gains with mypy in CI.
Three bugs meet three gates: swapped order and customer IDs are stopped by mypy and NewType as the code is written; an odd “closed” status slips past mypy but is stopped by Pydantic on data intake; an order the customer does not own is stopped only by a hand-written access check.
Static analysis catches IDs passed in the wrong order and Pydantic holds back mistyped records, but order ownership must still be checked by hand. Source: hypothetical example in the article, based on Python, mypy and Pydantic documentation

Python’s official documentation is blunt: the runtime does not enforce function and variable type annotations. You write int, someone passes in a string, and the declaration by itself stops nothing. Yet Patrick Viafore has written a 380-page book on getting the most out of this type system.

Robust Python, subtitled Write Clean and Maintainable Code, was published by O’Reilly Media on July 12 2021 (book page). It covers the types you define yourself, such as classes and enums, along with Python’s type hints. The example below was built separately to apply that subject to FDE work and does not come from the book; the material on NewType, mypy and Pydantic draws on each tool’s documentation.

For FDEs, the skill bears directly on the job. If you have to hand over code that processes a customer’s data to another team, good types record in the code itself the assumptions you may no longer be around to explain.

The cheapest bug is the one you just typed

The first idea to keep concerns timing. Episode 332 of the Talk Python To Me podcast, which discusses the book, holds that the best time to catch a bug is right after writing it. The tools for that are your editor and static analysis such as mypy.

Take a hypothetical order system with a function cancel(order_id, customer_id), where both parameters are int. Customer 88 wants to cancel order 1042, but you call cancel(88, 1042). Python runs it and the type checker stays silent too, because two integers are still two integers. If the function does not check who owns the order, someone else’s order 88 may be canceled.

Declaring int does not save you, because it cannot tell an order ID from a customer ID. The Python documentation offers a remedy in NewType: it creates a distinct type from a base type, which static type checkers treat as a subtype, helping to catch logic errors. The code below still swaps the arguments on purpose:

from enum import Enum
from typing import NewType
from pydantic import BaseModel, ValidationError

OrderId = NewType("OrderId", int)
CustomerId = NewType("CustomerId", int)

class Status(Enum):
    OPEN = "open"
    CANCELLED = "cancelled"

class Order(BaseModel):
    order_id: OrderId
    customer_id: CustomerId
    status: Status

def cancel(order_id: OrderId, customer_id: CustomerId) -> None:
    print(f"cancel {order_id} for {customer_id}")

def handle(raw: dict[str, object]) -> None:
    order = Order.model_validate(raw)
    cancel(order.customer_id, order.order_id)

This time mypy reports the wrong type for both arguments on the last line, before any order is touched (file name and line numbers omitted):

error: Argument 1 to "cancel" has incompatible type "CustomerId"; expected "OrderId"  [arg-type]
error: Argument 2 to "cancel" has incompatible type "OrderId"; expected "CustomerId"  [arg-type]

Swap the two arguments back and the errors disappear:

    cancel(order.order_id, order.customer_id)

To get that result, the new types must run the whole route: the two NewType lines, the signature of cancel and both fields in Order. If the fields in Order were still int, mypy would reject even the correct call.

The first job at a customer is to hunt down functions that take two or more identifiers, then separate the types from where the data originates to where it is used.

mypy cannot see the customer’s files

Do not leave all the guard duty to mypy, though. The same podcast episode concedes that a type checker does not catch every error; it only catches more of them. For FDEs the biggest gap is in the data: the CSV file arriving tomorrow morning does not exist when you run static analysis.

That is the role of Order.model_validate(raw) in the example. Pydantic’s documentation guarantees that after parsing and validation, the fields of a model instance conform to the declared types. If the source sends the status "closed", a value not in the Status enum, the record is stopped at the door.

A blocked record has yet to be dealt with. In the version of handle above, the error is simply raised and nobody keeps the record. The revision below stores it with the reason, and makes the call with the arguments in the right order:

rejected: list[tuple[dict[str, object], str]] = []

def handle(raw: dict[str, object]) -> None:
    try:
        order = Order.model_validate(raw)
    except ValidationError as e:
        rejected.append((raw, str(e)))
        return
    cancel(order.order_id, order.customer_id)

The rejected list is only for illustration; on a real project, write to a table or file so nothing is lost when the program stops. Then take each reason to the team that owns the data, because "closed" may be a valid status nobody has told you about.

Correct types do not guarantee correct business logic either. This model does not know whether order 1042 exists, or whether customer 88 owns it; you still have to check permissions yourself.

Do not type the whole codebase

Once NewType proves its worth, it is tempting to spread types over every file. The podcast offers a reality check: gradual typing lets you add types only where they make sense, and you should aim first at the code that produces value. In the example above, the function that cancels orders comes before a one-off report export script.

For a large existing codebase, the mypy documentation advises choosing a subset, say 5,000 to 50,000 lines, and getting mypy to run successfully on it before adding annotations. Then put mypy into CI so new type errors cannot slip in. That order suits customer projects, because it gives you a clear point of completion to hand over.

Who should read it, and in what order

The book is best suited to engineers who already write Python fluently but still use dict and strings for everything. If you are learning basic syntax, leave it for later.

The route suggested here follows two subjects the book presents, type hints and user-defined types, rather than its chapter order. Newcomers to typing should begin with type hints, then move on to enums and classes. If you already know mypy, you can go straight to user-defined types.

After that, open the example code repository. Its README notes that many examples use dummy types and data, while the core remains as in the book. Since the book dates from 2021, check the syntax against the current typing documentation before copying it into a project.

When you finish, turn it into career evidence. When an FDE job posting mentions production Python or data integration, a small repo with a Pydantic model, two distinct ID types and mypy running in CI will persuade more than the line “proficient in Python”. On your résumé, state the kinds of errors you blocked and the number of bad records held back, provided you really measured them.

And when an interviewer asks why you should declare something Python does not enforce, show them a commit in which you deliberately swapped the order ID and the customer ID. The red CI run is the answer.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
6 sources
Read next on the roadmap · Stage 1: FoundationsThe biggest part of SC-900 is not the part FDEs need mostEntra and Purview give you the vocabulary to ask whose permissions an agent uses to read data; Copilot's own rules require reading beyond the course.