Advertisement
Advanced Python, Decorators

How does functools.singledispatch let you implement function overloading based on an argument's TYPE?

Short answer

@functools.singledispatch turns a function into a GENERIC function that dispatches to different implementations based on the type of its FIRST argument — register additional type-specific implementations with @function_name.register(Type), and the correct one is chosen…

Save Python mock interview
Advertisement
AModel answer
@functools.singledispatch turns a function into a GENERIC function that dispatches to different implementations based on the type of its FIRST argument — register additional type-specific implementations with @function_name.register(Type), and the correct one is chosen automatically at call time.
from functools import singledispatch

@singledispatch
def describe(value):
    return f"A value: {value}"

@describe.register
def _(value: int):
    return f"An integer: {value}"

@describe.register
def _(value: list):
    return f"A list of {len(value)} items"

print(describe(42))       # "An integer: 42"
print(describe([1,2,3]))  # "A list of 3 items"
Real-world example
Implementing type-based dispatch for a serialization or rendering function that behaves differently based on input type.
Likely follow-ups
  • How does functools.singledispatchmethod extend this same capability to instance methods inside a class?
Related topics