Skip to content

.tip

· one of the small things

typing.Protocol for 'anything with these methods'

A function that takes a Repository should accept anything with get and save, including the fake in your test, without the fake having to inherit from anything.

class Repository(Protocol):
    def get(self, id: str) -> Order | None: ...
    def save(self, order: Order) -> None: ...

It's structural, the type checker checks it, and you don't need a base class. That's how duck typing and static types stop fighting each other.

python