singledispatch Routes By Argument Type
Format mixed report values with functools.singledispatch: one str fallback plus registered int, Decimal, date, and list branches replace isinstance chains.
Code
import functools
from datetime import date
from decimal import Decimal
@functools.singledispatch
def render(value):
return str(value) # 兜底分支:未注册类型一律 str()
@render.register
def _(value: int):
return f"{value:,}"
@render.register
def _(value: Decimal):
return f"{value:.2f}"
@render.register
def _(value: date):
return value.isoformat()
@render.register(list)
def _(value):
return f"[{', '.join(render(item) for item in value)}]"
row = {"count": 1204567, "amount": Decimal("3.5"), "day": date(2026, 11, 12), "tags": ["a", "b"]}
for key, value in row.items():
print(f"{key:>7}: {render(value)}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
count: 1,204,567
amount: 3.50
day: 2026-11-12
tags: [a, b]How the snippet works
singledispatch Routes By Argument Type comes down to the functions render and _.
Iteration happens inside for key, value in row.items() — everything outside it runs once. The import line is the dependency contract: date, Decimal come from decimal and nothing else.
Watch out for
- Requires
decimalas a package; the snippet will not run without it.
Applying it
The primary signature is def render(value)
Treat render as the API: import it, and ignore the supporting code.
Statements that matter
return f"[{', '.join(render(item) for item in value)}]"
row = {"count": 1204567, "amount": Decimal("3.5"), "day": date(2026, 11, 12), "tags": ["a", "b"]}
def _(value: Decimal):
return f"{value:.2f}"
def _(value: date):
return value.isoformat()
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `render`, `_` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.