Python › functools & Functional Programming Tools
How does functools.singledispatch enable function overloading based on argument type?
AdvancedAnswer
singledispatch turns a function into a generic function that dispatches to type-specific implementations registered with @func.register(Type). The base function acts as the default implementation, and Python picks the most specific matching registered implementation based on the first argument's runtime type.
from functools import singledispatch
@singledispatch
def describe(obj):
return f'object: {obj}'
@describe.register
def _(obj: int):
return f'integer: {obj}'
@describe.register
def _(obj: list):
return f'list of {len(obj)} items'
print(describe(5), describe([1,2,3]))Real-world example A serialization library uses singledispatch to convert different Python types (int, list, datetime) to JSON-compatible representations without a long if/elif chain.