Sub topic 2
Narrowing Types with Python Type Checkers
This chapter assumes you can write Python 3 functions and use annotations. It also assumes you can run mypy or Pyright from a virtual environment.
Narrowing with `isinstance`, `None`, and conditions
A union type says that a value may have more than one type. Type narrowing is the process of proving which type applies on a particular code path.
def describe(value: int | str | None) -> str:
if value is None:
return "missing"
if isinstance(value, int):
return f"number: {value + 1}"
return f"text: {value.upper()}"After value is None, the checker removes None from the possible types. After isinstance(value, int), it knows that the value is an int. The final branch contains only str.
`Any` and gradual typing
Any means “skip type checking here.” It can pass into or out of almost any typed expression, so use it at boundaries such as untyped legacy code, not throughout new code.
Unannotated functions can also reduce checking. Add annotations at module boundaries first, then expand inward.
> callout tip > A successful type-checking run does not prove runtime safety. It cannot validate user input, network responses, or incorrect annotations.
Generic functions with `TypeVar`
A TypeVar connects an input type to an output type. This preserves useful information:
from typing import Sequence, TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
number = first([1, 2, 3]) # int
word = first(["a", "b"]) # strStructural typing with `Protocol`
A Protocol describes the methods an object must provide. The class does not need to inherit from the protocol.
from typing import Protocol
class Closeable(Protocol):
def close(self) -> None: ...
def shutdown(resource: Closeable) -> None:
resource.close()Any object with a compatible close method can be passed to shutdown.
Typed dictionaries and dataclasses
TypedDict checks dictionary keys and values. A dataclass defines a typed object with generated methods such as __init__.
| Construct | Best for |
|---|---|
| `TypedDict` | JSON-like records and dictionaries |
| `dataclass` | Application objects with fields and behavior |
Use TypedDict for data-shaped mappings and dataclasses when the value has identity or behavior.
Exercise
Why does a None check allow a checker to accept name.upper() afterward?
Show answer
The check removes None from the union on the remaining code path, narrowing the value to str.