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 typing1from typing import Protocol, runtime_checkable2 # Enable runtime isinstance checks3@runtime_checkable# Define protocol specifying required methods4class Drawable(Protocol): # Signature only; ... stands in for the body5 def draw(self) -> str: ...6 # Class implementing the protocol implicitly7class Circle: # Implements draw method8 def draw(self) -> str: # Return a description string9 return "Drawing circle"10 # Another class implementing the protocol11class Square: # Implements draw method12 def draw(self) -> str: # Return a description string13 return "Drawing square"14 # Function accepting any Drawable15def render(shape: Drawable) -> None: # Call draw and print result16 print(shape.draw())17 # Create list of shapes18shapes = [Circle(), Square()]# Iterate and render each shape19for s in shapes: # isinstance only checks that a draw method exists, not its signature20 if isinstance(s, Drawable): # Render the shape21 render(s)Output
Drawing circle Drawing square
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