typestar

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

  1. @singledispatch defines the fallback.
  2. @name.register adds a typed implementation.
  3. It replaces a chain of isinstance checks.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in functools & operator, step 39 of 53 in Pythonic Python.

← Previous Next →