Choose Behavior with singledispatch
Core idea
functools.singledispatch(fn) creates a generic callable with a default implementation. Register an implementation using generic.register(SomeType, implementation). Calls choose an implementation based on the type of the first positional argument, using applicable base classes when no exact registration exists. This lesson uses direct calls instead of decorator syntax.
from functools import singledispatchdef describe(value): return "other"def describe_int(value): return "number:" + str(value)show = singledispatch(describe)show.register(int, describe_int)print(show(7), show("A"))The integer uses the registered implementation; the string uses the default.
Observe subclass dispatch
from functools import singledispatchdef default(value): return "other"def number(value): return "integer"show = singledispatch(default)show.register(int, number)print(show(True))bool inherits from int, so the int registration applies.
Override with an exact type
from functools import singledispatchdef default(value): return "other"show = singledispatch(default)show.register(int, lambda value: "integer")show.register(bool, lambda value: "flag")print(show(True), show(1))The more specific bool registration takes precedence for True.
Common mistake
Single dispatch is not dispatch on all argument types or argument values. A list of integers and a list of strings have the same runtime type list; registering list does not distinguish their element types.
Practice
Register handlers for str and list that return their length with a descriptive label. Provide a default for unsupported objects, and test empty strings and lists.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Single dispatch
Check your understanding of single dispatch.
What is printed?
from functools import singledispatchf = singledispatch(lambda x: "other")f.register(int, lambda x: "int")print(f(2), f("2"))What is printed?
from functools import singledispatchf = singledispatch(lambda x: "other")f.register(int, lambda x: "integer")print(f(False))What is printed?
from functools import singledispatchf = singledispatch(lambda x: "other")f.register(int, lambda x: "integer")f.register(bool, lambda x: "flag")print(f(True))What determines ordinary singledispatch selection?