Format by Type with singledispatch
Hard · Functions
functools.singledispatch turns a function into a generic function that picks an implementation based on the type of its first argument. You register implementations with @fmt.register(int), or with @fmt.register above a function with a type hint like def _(value: int). Python picks the most specific type, so a bool implementation wins over int even though bool is a subclass of int.
Complete fmt(value) so it formats:
- None → "-"
- bool → "yes" or "no"
- int → with thousands separators: 1234567 → "1,234,567"
- float → two decimals with separators: 1234.5 → "1,234.50"
- str → wrapped in double quotes: hi → "hi"
- list → "[a, b]", every item formatted with fmt
- dict → "{key: value, ...}", keys as they are, values formatted with fmt
The driver format_all(values) is already written and returns [fmt(v) for v in values].