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 typing
1from typing import Protocol, runtime_checkable
2
# @runtime_checkable would allow isinstance() checks (unused below)
3@runtime_checkable
# class Transformer(Protocol) defines callable interface
4class Transformer(Protocol):
# __call__ with signature defines the callable contract
5 def __call__(self, value: str) -> str: ...
6
# UpperCase matches Transformer without inheriting from it
7class UpperCase:
# __call__ makes instances callable
8 def __call__(self, value: str) -> str:
# Returns uppercase version of input
9 return value.upper()
10
# class AddPrefix also implements Transformer protocol
11class AddPrefix:
# __init__ stores the prefix to use
12 def __init__(self, prefix: str):
# Save prefix as instance attribute
13 self.prefix = prefix
14
# __call__ makes instances callable
15 def __call__(self, value: str) -> str:
# Returns prefix concatenated with value
16 return f"{self.prefix}{value}"
17
# apply_transform accepts any Transformer-compatible callable
18def apply_transform(text: str, transformer: Transformer) -> str:
# Call the transformer with the text
19 return transformer(text)
20
# Apply UpperCase transformer
21print(apply_transform("hello", UpperCase()))
# Apply AddPrefix transformer
22print(apply_transform("world", AddPrefix(">>> ")))

Output

HELLO
>>> world
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.

  • _× 21
  • :× 14
  • (× 14
  • )× 14
  • ,× 8
  • "× 8
  • >× 7
  • .× 6
  • -× 4
  • {× 2

More Python examples at level 5

← Python typing practice