# 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.

Original: https://fdetimes.net/en/books-courses/robust-python-type-hints-fde/

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](https://www.oreilly.com/library/view/robust-python/9781098100650/)). 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:

```python
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):

```text
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:

```python
    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.

**Key point:** A type only catches an error when it says what the business means.

## 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:

```python
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](https://github.com/pviafore/RobustPython). 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](https://docs.python.org/3/library/typing.html) 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.

**Try this week:**

- Find a function that takes two identifiers of the same type, int or str, switch them to NewType, then swap them on purpose to see what mypy reports.
- Write a Pydantic model for the data source that causes the most incidents and pass every record through it before processing.
- Put mypy into CI for a single important module.

## Sources

- [Robust Python by Patrick Viafore on Apple Books](https://books.apple.com/us/book/robust-python/id1576261902)

- [GitHub - pviafore/RobustPython: Code Examples for Robust Python book](https://github.com/pviafore/RobustPython)

- [Talk Python To Me, Episode #332 - Robust Python (transcript)](https://talkpython.fm/episodes/transcript/332/robust-python)

- [typing — Support for type hints](https://docs.python.org/3/library/typing.html)

- [Using mypy with an existing codebase](https://mypy.readthedocs.io/en/stable/existing_code.html)

- [Models | Pydantic Docs](https://pydantic.dev/docs/validation/latest/concepts/models/)
