typestar

Protocols in Python

Structural typing: duck typing the type checker understands.

from typing import Protocol


class Drawable(Protocol):
    def draw(self) -> str: ...


class Circle:
    def draw(self) -> str:
        return "( )"


class Square:
    def draw(self) -> str:
        return "[ ]"


def render(shapes: list[Drawable]) -> str:
    return " ".join(s.draw() for s in shapes)

How it works

  1. A Protocol lists the methods a type must have.
  2. Circle and Square match it without inheriting.
  3. render accepts anything shaped like Drawable.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
273
Tokens
84
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 5 of 5 in Protocols & context managers, step 19 of 53 in Pythonic Python.

← Previous Next →