functools.singledispatch
Prev: functools.reduce | Up: functools | Next: functools.singledispatchmethod
Rel: functools.cache, functools.cached_property, functools.cmp_to_key, functools.lru_cache
Ref: docs.python.org — functools.singledispatch
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import singledispatch
Signature & Overview
functools.singledispatch(func)
Single-dispatch generic function decorator.
Usage
from functools import singledispatch
@singledispatch
def summarize(value) -> str:
return f"other:{value}"
@summarize.register
def _(value: int) -> str:
return f"int:{value * 2}"
@summarize.register
def _(value: list) -> str:
return f"list:{len(value)}"
assert summarize(5) == "int:10"
assert summarize([1, 2, 3]) == "list:3"
assert summarize("hi") == "other:hi"
Gotchas
- Dispatches on the first positional argument only: Keyword arguments or additional parameter types are ignored for dispatch.
- Supports unions and ABCs: You can register
@fn.registeronint | floatorcollections.abc.Sequence, and usesingledispatchmethodfor class methods.
REPL Inspect
from functools import singledispatch
help(singledispatch)
Linked from
Related notes
- tuts/python3/stdlib_module/functools/reduce Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatchmethod 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/total_ordering shared tags: #functools, #stdlib