On this page
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
singledispatchmethod.register(self, cls, method=None)— Registers a new implementation for the given cls on a generic_method.
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
- Dispatches on the first argument after
self/cls: Plain@singledispatchon a method would mistakenly dispatch onselfinstead. - Decorator order with
@classmethod/@staticmethod: Put@singledispatchmethodoutside@classmethod(i.e.@singledispatchmethodon top).
REPL Inspect
from functools import singledispatchmethod
help(singledispatchmethod)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/singledispatch Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/total_ordering Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cmp_to_key Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partialmethod shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/reduce shared tags: #functools, #stdlib