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.

PythonCli Tooling

Code

pythonsnippet
27 lines
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 decimal as 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

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.