On this page
  1. functools.singledispatchmethod
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

functools.singledispatchmethod

Prev: functools.singledispatch | Up: functools | Next: functools.total_ordering
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.singledispatchmethod
Tags: #public #python3 #stdlib #functools


Import

import functools
from functools import singledispatchmethod

Signature & Overview

functools.singledispatchmethod(func)

Single-dispatch generic method descriptor.

Methods & Attributes

Usage

from functools import singledispatchmethod

class Formatter:
    @singledispatchmethod
    def fmt(self, arg) -> str:
        return str(arg)

    @fmt.register
    def _(self, arg: int) -> str:
        return f"{arg:,}"

    @fmt.register
    def _(self, arg: bool) -> str:
        return "yes" if arg else "no"

f = Formatter()
assert f.fmt(1000) == "1,000" and f.fmt(True) == "yes"

Gotchas

REPL Inspect

from functools import singledispatchmethod
help(singledispatchmethod)

Linked from

Related notes