Python Type Hints and Code Quality · Lesson 134 of 149

Python Optional, Union, Generics and Protocols

What you will learn

  • Optional, Union and narrowing by isinstance and is None
  • Type variables and generic functions
  • Generic classes, with the old TypeVar form and the new class Box[T] syntax
  • Protocols: checking behaviour instead of ancestry
  • reveal_type, and what mypy tells you

1. Unions and Optional

Lesson 19.1 introduced X | None. The general form A | B means "an A or a B", called a union. The older spellings still appear in existing code:

Modern (3.10+) Older
int | str Union[int, str]
str | None Optional[str]

Optional[X] simply means X | None: a value that may be missing, not an argument that may be left out.

Before you can use a value of a union type, you must find out which member you have. The checker follows isinstance and is None checks and narrows the type in each branch:

def describe(value: int | str | list[int]) -> str:
    if isinstance(value, int):
        return "int"
    elif isinstance(value, str):
        return "str"
    reveal_type(value)
    return "list"

reveal_type(x) is a special call that mypy understands: it reports the type it has worked out. (Python 3.11 and later also has typing.reveal_type, which at run time only prints Runtime type is 'int' and returns its argument.) Here mypy reported:

note: Revealed type is "list[int]"

After excluding int and str, only list[int] remains. Without a check, the use of a union is refused:

def maybe(value: int | None = None) -> int:
    return value + 1
error: Unsupported operand types for + ("None" and "int")  [operator]
note: Left operand is of type "int | None"
Quick check: does `Optional[int]` mean the caller may omit the argument?

No. It means the value may be an int or None. Omitting an argument needs a default value.

2. Type variables and generic functions

Some functions work for any type but keep the connection between input and output: first(items) returns an item of the same type as the list holds. A hint of Any loses that link. A type variable keeps it:

from collections.abc import Sequence
from typing import TypeVar

T = TypeVar("T")


def first(items: Sequence[T]) -> T:
    return items[0]


def pair(a: T, b: T) -> list[T]:
    return [a, b]

T stands for "whatever type is used at the call". mypy fills it in for each call:

n: int = first([1, 2, 3])
s: str = first(["a"])
bad: str = first([1, 2])
reveal_type(first([1.5]))
reveal_type(pair(1, "x"))
error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
note: Revealed type is "float"
note: Revealed type is "list[object]"
  • first([1, 2, 3]) is an int, so assigning it to n: int is fine, and bad: str = first([1, 2]) is an error.
  • first([1.5]) is revealed as float.
  • pair(1, "x") mixes an int and a str; the common type mypy finds is object.

You can limit a type variable: TypeVar("N", int, float) allows only those types, and TypeVar("B", bound=Base) allows Base and its subclasses.

The newer syntax (Python 3.12)

Python 3.12 added a cleaner way to write generics, with the type variable in square brackets right after the name, with no TypeVar line:

def biggest[V: (int, float)](a: V, b: V) -> V:
    return a if a > b else b


reveal_type(biggest(1, 2))
note: Revealed type is "int"

Use the older form if you must support Python before 3.12.

3. Generic classes

A container class can be generic: a stack that holds integers, or strings, but always one kind at a time.

from typing import Generic, TypeVar

T = TypeVar("T")


class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()


ints: Stack[int] = Stack()
ints.push(1)
ints.push("x")
reveal_type(ints.pop())
error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"  [arg-type]
note: Revealed type is "int"

Stack[int] is a stack of integers: pushing a string is reported, and pop is known to give an int. The built-in list[int], dict[str, int] and set[str] are generic classes written in just this way. With Python 3.12 the same class is shorter:

class Stack2[U]:
    def __init__(self) -> None:
        self.items: list[U] = []

    def push(self, item: U) -> None:
        self.items.append(item)

4. Protocols: typing by behaviour

Python code often relies on duck typing (lesson 13.6): "if it has a speak method, I can use it." A normal type hint would make you inherit from a common base class. A Protocol describes the needed methods instead, and any class that has them matches, with no inheritance:

from typing import Protocol


class Speaker(Protocol):
    def speak(self) -> str: ...


class Dog:
    def speak(self) -> str:
        return "Woof"


class Rock:
    pass


class Cat:
    def speak(self, loud: bool) -> str:
        return "Meow"


def talk(x: Speaker) -> str:
    return x.speak()


print(talk(Dog()))
talk(Rock())
talk(Cat())

Dog never mentions Speaker, yet talk(Dog()) is accepted. mypy rejects the other two and explains exactly why:

error: Argument 1 to "talk" has incompatible type "Rock"; expected "Speaker"  [arg-type]
error: Argument 1 to "talk" has incompatible type "Cat"; expected "Speaker"  [arg-type]
note: Following member(s) of "Cat" have conflicts:
note:     Expected:
note:         def speak(self) -> str
note:     Got:
note:         def speak(self, loud: bool) -> str

A Cat has a speak, but with a different signature, so it does not fit. The ... in a protocol method body means "no implementation here". This is structural typing: compatibility depends on the shape, not the family tree. Compare with abstract base classes (lesson 13.10), which require inheriting.

At run time a Protocol does nothing unless marked @runtime_checkable, which lets isinstance test for the presence of the methods (not their signatures):

from typing import Protocol, runtime_checkable


@runtime_checkable
class S(Protocol):
    def speak(self) -> str: ...


class D:
    def speak(self):
        return "w"


print(isinstance(D(), S), isinstance(3, S))
True False

Why Protocols help

  • Functions can accept "anything with a read() method" or "anything with save and load", which keeps code flexible and easy to test with fake objects (lesson 13.9).
  • Library code can describe what it needs without forcing users to inherit from its classes.
  • The standard library's Iterable, Sized, Callable and friends (lesson 13.10) are protocol-like types.

5. Other useful hints

Hint Meaning
Callable[[A, B], R] a function from A and B to R
Self the type of the current class, for methods that return self
Never / NoReturn a function that never returns (always raises)
Annotated[T, meta] a type with extra information for other tools
@overload several signatures for one function
cast(T, x) tell the checker "trust me" (it checks nothing at run time)
TYPE_CHECKING code imported only for the checker (avoids circular imports)

Use Any and cast rarely: each is a hole in the safety net.

Worked example: a notes app that accepts any storage

Notes works with anything that can save and load text, described by a Protocol. A generic Box[T] shows how types flow through map. The last two lines are mistakes on purpose.

from collections.abc import Callable
from dataclasses import dataclass
from typing import Protocol


class Storage(Protocol):
    def save(self, key: str, value: str) -> None: ...
    def load(self, key: str) -> str | None: ...


class MemoryStorage:
    def __init__(self) -> None:
        self.data: dict[str, str] = {}

    def save(self, key: str, value: str) -> None:
        self.data[key] = value

    def load(self, key: str) -> str | None:
        return self.data.get(key)


class BrokenStorage:
    def save(self, key: str) -> None:
        pass


class Box[T]:
    """Holds one value of any type and gives it back with the same type."""

    def __init__(self, value: T) -> None:
        self.value = value

    def map[R](self, f: Callable[[T], R]) -> "Box[R]":
        return Box(f(self.value))


@dataclass
class Notes:
    storage: Storage

    def add(self, title: str, text: str) -> None:
        self.storage.save(title, text)

    def read(self, title: str) -> str:
        text = self.storage.load(title)
        return text if text is not None else "(no such note)"


notes = Notes(MemoryStorage())
notes.add("todo", "buy milk")
print(notes.read("todo"), "|", notes.read("missing"))

length: Box[int] = Box("hello").map(len)
shout: Box[str] = Box("hello").map(str.upper)
print(length.value, shout.value)

wrong = Notes(BrokenStorage())
bad_number: Box[str] = Box(3)

Running the program prints (the two mistakes do not fail at run time, because hints are not enforced):

buy milk | (no such note)
5 HELLO

mypy reports the two mistakes:

error: Argument 1 to "Notes" has incompatible type "BrokenStorage"; expected "Storage"  [arg-type]
note: "BrokenStorage" is missing following "Storage" protocol member:
note:     load
note: Following member(s) of "BrokenStorage" have conflicts:
note:     Expected:
note:         def save(self, key: str, value: str) -> None
note:     Got:
note:         def save(self, key: str) -> None
error: Argument 1 to "Box" has incompatible type "int"; expected "str"  [arg-type]
Idea Where
Protocol Storage: MemoryStorage matches without inheriting; BrokenStorage lacks load and has a wrong save
str | None and narrowing read handles the None from load
generic class Box[T]: Box("hello").map(len) is a Box[int], .map(str.upper) a Box[str]
mypy's explanation it lists the missing member and the signature mismatch

The notes are made up. In a real project the Storage protocol would also be implemented by a file or database class (lesson 17.10), and a test could use the in-memory one.

Common mistakes

  • Confusing Optional[X] with an optional argument.
  • Using Any where a type variable or union would keep the checks.
  • Using a protocol when a simple union is enough, or the reverse.
  • Making a class inherit from a Protocol just to satisfy it (not needed).
  • Expecting isinstance(x, SomeProtocol) to work without @runtime_checkable (and expecting it to check signatures).
  • Forgetting the generic argument (Stack instead of Stack[int]), which loses the checking.
  • Using Python 3.12 syntax on older Python.
  • Treating mypy errors as noise instead of reading the notes that explain them.

Key takeaways

  • A | B is a union; checks with is None and isinstance narrow it; Optional[X] means X | None.
  • A TypeVar (or the Python 3.12 def f[T](...)) links input and output types in generic functions and classes such as Stack[int].
  • A Protocol describes the methods an argument must have, so any matching class is accepted without inheriting from anything.
  • reveal_type and mypy's notes show what the checker believes and why it complains.
  • Keep hints as simple as the code allows; use Any and cast sparingly.

Practice

1. What does Optional[str] mean?

Show answer

str | None: either a string or None.

2. Why use a TypeVar in def first(items: Sequence[T]) -> T?

Show answer

It records that the returned item has the same type as the list's items, which Any would lose.

3. What does Stack[int] express?

Show answer

A stack that holds integers; pushing another type is reported by the checker, and pop is known to give an int.

4. How does a Protocol differ from an abstract base class?

Show answer

A class matches a Protocol just by having the right methods, with no inheritance; an abstract base class must be inherited from.

5. After if isinstance(v, int): return in a function with v: int | str, what type does v have below?

Show answer

str, because the checker narrows the union after the int case returned.

6. Write a Protocol for objects with a close() method returning nothing.

Show answer
class Closeable(Protocol):
    def close(self) -> None: ...