Type Checking Protocol in Python

Level 5387 keystrokes

This uses typing.Protocol with @runtime_checkable to define structural subtyping that can be checked at runtime.

Python code

# Import Protocol and runtime_checkable from typing
1from typing import Protocol, runtime_checkable
2
# Enable runtime isinstance checks
3@runtime_checkable
# Define protocol specifying required methods
4class Drawable(Protocol):
# Signature only; ... stands in for the body
5 def draw(self) -> str: ...
6
# Class implementing the protocol implicitly
7class Circle:
# Implements draw method
8 def draw(self) -> str:
# Return a description string
9 return "Drawing circle"
10
# Another class implementing the protocol
11class Square:
# Implements draw method
12 def draw(self) -> str:
# Return a description string
13 return "Drawing square"
14
# Function accepting any Drawable
15def render(shape: Drawable) -> None:
# Call draw and print result
16 print(shape.draw())
17
# Create list of shapes
18shapes = [Circle(), Square()]
# Iterate and render each shape
19for s in shapes:
# isinstance only checks that a draw method exists, not its signature
20 if isinstance(s, Drawable):
# Render the shape
21 render(s)

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
  • :× 10
  • -× 4
  • .× 4
  • "× 4
  • >× 4
  • ,× 3
  • _× 2
  • [× 1

More Python examples at level 5

← Python typing practice