Protocol Typing in Python

Level 5298 keystrokes

This uses Protocol for structural subtyping. Classes don't need to inherit from Protocol, just implement the required methods.

Python code

# Import Protocol from typing module
1from typing import Protocol
2
# Define protocol with required method signature
3class Drawable(Protocol):
# Method signature only, no implementation
4 def draw(self) -> str: ...
5
# Circle class implements draw method
6class Circle:
# Implementation of draw method
7 def draw(self) -> str:
# Return string describing the shape
8 return "Drawing circle"
9
# Square class implements draw method
10class Square:
# Implementation of draw method
11 def draw(self) -> str:
# Return string describing the shape
12 return "Drawing square"
13
# Function accepts any Drawable protocol implementer
14def render(shape: Drawable) -> None:
# Call draw method and print result
15 print(shape.draw())
16
# Render circle - works because Circle has draw()
17render(Circle())
# Render square - works because Square has draw()
18render(Square())

Output

Drawing circle
Drawing square
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 11
  • )× 11
  • :× 8
  • -× 4
  • .× 4
  • "× 4
  • >× 4

More Python examples at level 5

← Python typing practice