Dispatching just means -
“Deciding which function to call based on input”
Let’s see it step by step..
add = lambda x, y: x + y
sub = lambda x, y: x - y
def dispatch(op, x, y):
return op(x, y)
dispatch(add, 2, 3) # 5
Here, we pass the function itself.
operations = {
"add": lambda x, y: x + y,
"sub": lambda x, y: x - y
}
def dispatch(op, x, y):
return operations[op](x, y)
dispatch("add", 2, 3) # 5
No if-else, easy to extend.
class Dog:
def say(self): return "woof"
class Cat:
def say(self): return "meau"
def process(animal):
return animal.say()
process(Dog()) # woof
process(Cat()) # meau
Python decides which method to call at runtime.
singledispatch)from functools import singledispatch
@singledispatch
def process(x):
return "default"
@process.register
def _(x: int):
return "it's integer"
@process.register
def _(x: float):
return "it's float"
process(10) # it's integer
process(2.5) # it's float
process("hi") # default
👉 Dispatch based on input type.
Dispatch = “Who should handle this input?”
That’s it. Simple, powerful, and used everywhere.