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 module1from typing import Protocol2 # Define protocol with required method signature3class Drawable(Protocol): # Method signature only, no implementation4 def draw(self) -> str: ...5 # Circle class implements draw method6class Circle: # Implementation of draw method7 def draw(self) -> str: # Return string describing the shape8 return "Drawing circle"9 # Square class implements draw method10class Square: # Implementation of draw method11 def draw(self) -> str: # Return string describing the shape12 return "Drawing square"13 # Function accepts any Drawable protocol implementer14def render(shape: Drawable) -> None: # Call draw method and print result15 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. 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