Callable Protocol in Python
Level 5547 keystrokes
This uses Protocol with __call__ to define a callable interface that classes can implement.
Python code
# Import Protocol and runtime_checkable for structural typing1from typing import Protocol, runtime_checkable2 # @runtime_checkable would allow isinstance() checks (unused below)3@runtime_checkable# class Transformer(Protocol) defines callable interface4class Transformer(Protocol): # __call__ with signature defines the callable contract5 def __call__(self, value: str) -> str: ...6 # UpperCase matches Transformer without inheriting from it7class UpperCase: # __call__ makes instances callable8 def __call__(self, value: str) -> str: # Returns uppercase version of input9 return value.upper()10 # class AddPrefix also implements Transformer protocol11class AddPrefix: # __init__ stores the prefix to use12 def __init__(self, prefix: str): # Save prefix as instance attribute13 self.prefix = prefix14 # __call__ makes instances callable15 def __call__(self, value: str) -> str: # Returns prefix concatenated with value16 return f"{self.prefix}{value}"17 # apply_transform accepts any Transformer-compatible callable18def apply_transform(text: str, transformer: Transformer) -> str: # Call the transformer with the text19 return transformer(text)20 # Apply UpperCase transformer21print(apply_transform("hello", UpperCase()))# Apply AddPrefix transformer22print(apply_transform("world", AddPrefix(">>> ")))Output
HELLO >>> world
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.
_× 21:× 14(× 14)× 14,× 8"× 8>× 7.× 6-× 4{× 2