singledispatch in Python
One function name, an implementation chosen by the first argument's type.
from functools import singledispatch
@singledispatch
def summarize(value):
return f"{type(value).__name__}: {value!r}"
@summarize.register
def _(value: int):
return f"int: {value:+d}"
@summarize.register
def _(value: list):
return f"list of {len(value)}"
@summarize.register(str)
def _(value):
return f"text of {len(value)} chars"
for item in (3, "hello", [1, 2], 2.5):
print(summarize(item))
How it works
@singledispatchdefines the fallback.@name.registeradds a typed implementation.- It replaces a chain of isinstance checks.
Keywords and builtins used here
_defforintlenlistprintreturnstrsummarizetype
The run, in numbers
- Lines
- 25
- Characters to type
- 402
- Tokens
- 120
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 69 seconds.
Step 2 of 3 in functools & operator, step 39 of 53 in Pythonic Python.