Dispatching in Python (Simple & Practical)

Apr 9, 2026

Dispatching just means -

“Deciding which function to call based on input”

Let’s see it step by step..


1. Basic Dispatch (functions as arguments)

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.


2. Dictionary Dispatch (cleaner approach)

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.


3. Object Dispatch (dynamic dispatch)

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.


4. Type-based Dispatch (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.


Why it matters


Mental Model

Dispatch = “Who should handle this input?”


That’s it. Simple, powerful, and used everywhere.

go back to tech