Khush Shah

Replacing if/elif Chains in Python: Dictionaries and match

Khush Shah 12 min read Python, Tutorials

Machine-learning code is full of choices made by name. A config file says loss: mse, optimiser: adam or scheduler: cosine, an evaluation script takes --metric f1, and somewhere a function turns that string into the right object. The first version is usually an if/elif chain that grows by two lines every time someone adds an option. In this post, first published as Multiple Choice Functions, I write the same small dispatcher three ways (an if/elif chain, a dictionary of functions and a match statement), compare them on readability, extensibility, error handling and speed, and end with the two patterns I actually use: a registry filled in by a decorator, and match for the cases a dictionary cannot express.

The match statement was added in Python 3.10, so the code here needs Python 3.10 or newer. This is the version I ran it with:

import sys

print(sys.version)
assert sys.version_info >= (3, 10), "match needs Python 3.10 or newer"
3.12.12 | packaged by conda-forge | (main, Oct 13 2025, 14:47:45) [Clang 19.1.7 ]

The four operations

The task is deliberately small: apply one of four arithmetic operations, chosen by name, to two numbers. Here they are as plain functions, each with type hints and a docstring.

def add(a: float, b: float) -> float:
    """Return a + b."""
    return a + b


def subtract(a: float, b: float) -> float:
    """Return a - b."""
    return a - b


def multiply(a: float, b: float) -> float:
    """Return a * b."""
    return a * b


def divide(a: float, b: float) -> float:
    """Return a / b. Raises ZeroDivisionError when b is 0."""
    return a / b

Two changes from the first version of this post. The function that adds was called sum, which hides Python's built-in sum for the rest of the notebook: after def sum(a, b), the call sum([1, 2, 3]) fails with TypeError: sum() missing 1 required positional argument: 'b'. So it is add now. And divide used to return the string "Error" when b was 0. A string in place of a number is a bug magnet: divide(1, 0) + 1 fails with a TypeError far from the cause, and divide(1, 0) * 2 quietly gives "ErrorError". Now a / b raises ZeroDivisionError on the line that caused it, which is what Python does anyway.

1. If-Else

def dispatch_if(task: str, a: float, b: float) -> float:
    """Apply the operation called `task` to a and b, using an if/elif chain."""
    if task == "add":
        return add(a, b)
    elif task == "subtract":
        return subtract(a, b)
    elif task == "multiply":
        return multiply(a, b)
    elif task == "divide":
        return divide(a, b)
    else:
        raise ValueError(f"unknown task: {task!r}")

The chain is the obvious version and needs nothing beyond the basics. Each option costs two lines, the name and the function sit on different lines, and the names are compared from the top down, so the last option pays for every comparison before it. Nothing forces the final else: leave it out and an unknown task silently returns None. The first version of this post returned the string "Invalid task" there, which has the same problem as "Error"; now an unknown task raises ValueError, and so will the other two versions. {task!r} prints the name with its quotes, so an empty string or a stray space shows up in the message.

The numbers are arguments too. The first version read a and b from global variables, so what the dispatcher returned depended on whatever those globals happened to hold.

2. Function Dictionary

from collections.abc import Callable

Operation = Callable[[float, float], float]

OPERATIONS: dict[str, Operation] = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


def dispatch_dict(task: str, a: float, b: float) -> float:
    """Apply the operation called `task` to a and b, looking it up in OPERATIONS."""
    operation = OPERATIONS.get(task)
    if operation is None:
        raise ValueError(f"unknown task: {task!r}")
    return operation(a, b)

Functions are ordinary objects in Python, so they can be values in a dictionary. The mapping from names to functions becomes data: one line per option, all in one place, and it can be printed, checked or extended without touching the dispatcher. The type hint Callable[[float, float], float] says that every value takes two numbers and returns one, which a type checker such as mypy can then enforce.

Looking a name up with OPERATIONS[task] raises KeyError for an unknown task, which is a different exception from the other two dispatchers and does not say that the problem is the task name. OPERATIONS.get(task) returns None instead, so I check for that and raise the same ValueError as the chain.

For arithmetic, the standard library already has these four functions in the operator module, so the dictionary needs no functions of its own:

import operator

OPS: dict[str, Operation] = {
    "add": operator.add,
    "subtract": operator.sub,
    "multiply": operator.mul,
    "divide": operator.truediv,
}

print({name: operation(3, 2) for name, operation in OPS.items()})
{'add': 5, 'subtract': 1, 'multiply': 6, 'divide': 1.5}

3. Match-Case

def dispatch_match(task: str, a: float, b: float) -> float:
    """Apply the operation called `task` to a and b, using a match statement."""
    match task:
        case "add":
            return add(a, b)
        case "subtract":
            return subtract(a, b)
        case "multiply":
            return multiply(a, b)
        case "divide":
            return divide(a, b)
        case _:
            raise ValueError(f"unknown task: {task!r}")

match compares the subject, task, with each case in turn and runs the first one that fits. For plain strings it reads like the if/elif chain without the repetition: the subject is written once and each option is a literal. It needs Python 3.10 or newer.

The last case is case _:, the wildcard, which matches anything. The first version of this post wrote case default:, which also works, but for a surprising reason: a bare name in a case is a capture pattern, which matches any value and assigns it to that name, so default became a new variable holding the task. The same rule is a trap when the name is meant as a constant:

match task:
    case add:          # does not compare task with the function add:
        ...            # it matches anything and rebinds add to the task
    case "subtract":
        ...

Python refuses to compile this one (SyntaxError: name capture 'add' makes remaining patterns unreachable), but only because another case follows it; as the last case it would quietly match everything. To compare with a constant, use a literal or a dotted name such as Task.ADD. _ is the one name that matches without binding anything, which is why case _: is the idiom.

Do they agree?

With the numbers passed in as arguments, the three dispatchers can be checked against each other on every task:

a, b = 3, 2
dispatchers = [dispatch_if, dispatch_dict, dispatch_match]

for task in ["add", "subtract", "multiply", "divide"]:
    print(f"{task:>8}:", [dispatch(task, a, b) for dispatch in dispatchers])
     add: [5, 5, 5]
subtract: [1, 1, 1]
multiply: [6, 6, 6]
  divide: [1.5, 1.5, 1.5]

And they fail in the same way:

for dispatch in dispatchers:
    try:
        dispatch("power", a, b)
    except ValueError as err:
        print(f"{dispatch.__name__}: ValueError: {err}")

try:
    OPERATIONS["power"]
except KeyError as err:
    print(f"OPERATIONS['power']: KeyError: {err}")

try:
    dispatch_dict("divide", a, 0)
except ZeroDivisionError as err:
    print(f"dispatch_dict('divide', 3, 0): ZeroDivisionError: {err}")
dispatch_if: ValueError: unknown task: 'power'
dispatch_dict: ValueError: unknown task: 'power'
dispatch_match: ValueError: unknown task: 'power'
OPERATIONS['power']: KeyError: 'power'
dispatch_dict('divide', 3, 0): ZeroDivisionError: division by zero

Speed

Is any of them faster? I timed each dispatcher with timeit: 1,000,000 calls per approach, split evenly over the four tasks, with each measurement repeated 7 times and the fastest kept, as the timeit documentation recommends (the slower runs mostly measure whatever else the machine was doing). The first row calls each operation directly, with no dispatch at all, to show what the call itself costs. I pass floats, 3.0 and 2.0, so that all four operations do the same kind of work; with small integers, only divide would create a new object.

import platform
import timeit

TASKS = ["add", "subtract", "multiply", "divide"]
CALLS = 1_000_000  # per approach, split evenly over the four tasks
REPEATS = 7  # keep the fastest of 7 runs
per_task = CALLS // len(TASKS)


def ns_per_call(stmt: str, **names) -> float:
    """Fastest of REPEATS runs of `stmt`, in nanoseconds per call."""
    times = timeit.repeat(stmt, globals=names, number=per_task, repeat=REPEATS)
    return min(times) / per_task * 1e9


rows = {"direct call": [ns_per_call("op(x, y)", op=OPERATIONS[t], x=3.0, y=2.0) for t in TASKS]}
for dispatch in dispatchers:
    rows[dispatch.__name__] = [
        ns_per_call("dispatch(t, x, y)", dispatch=dispatch, t=t, x=3.0, y=2.0) for t in TASKS
    ]

print(f"Python {platform.python_version()} on {platform.platform()}")
print(f"{CALLS:,} calls per approach, best of {REPEATS}, nanoseconds per call\n")
print(f"{'':>14}" + "".join(f"{t:>9}" for t in TASKS) + f"{'mean':>9}")
for name, row in rows.items():
    print(f"{name:>14}" + "".join(f"{ns:9.1f}" for ns in row) + f"{sum(row) / len(row):9.1f}")
Python 3.12.12 on macOS-27.2.1-arm64-arm-64bit
1,000,000 calls per approach, best of 7, nanoseconds per call

                    add subtract multiply   divide     mean
   direct call     23.8     21.9     22.1     24.8     23.2
   dispatch_if     41.1     43.7     49.2     52.0     46.5
 dispatch_dict     51.6     50.2     51.0     54.8     51.9
dispatch_match     43.1     47.0     50.9     55.8     49.2

These numbers come from Python 3.12 on an Apple silicon Mac (the first line of the output gives the exact version); on another machine they will differ. Across repeated runs here they moved by a nanosecond or two, and the order never changed. What they show:

  • The if/elif chain gets slower the further down the list the option is: 41.1 ns for add, the first, and 52.0 ns for divide, the fourth (about 2 ns of that is the division itself, which is slower in every row, including the direct call). match on string literals makes the same comparisons one after another and follows the same slope, 2 to 4 ns behind.
  • The dictionary costs the same for every option, about 28 to 30 ns on top of the direct call, because a lookup does not depend on where the key is. For four options it is the slowest of the three on average, 51.9 ns against 46.5 for the chain and 49.2 for match: one call to .get costs about as much as a few string comparisons. Its cost does not grow with the number of options; the chain's does.
  • A million calls take between 46 and 52 ms whichever way you choose.

So, for four options, speed is not a reason to choose. A loss or an optimiser is chosen once per run, not once per step, and even in a hot loop the difference is a few nanoseconds a call. The reasons to choose are readability, error handling and how easily the code grows.

Where match is better

match is much more than a switch on strings. Its patterns can look inside the value: unpack a tuple, compare some parts with constants, bind the other parts to names, and add a condition with if (a guard). Here is a function that says where a point lies:

def describe(point: tuple[float, float]) -> str:
    """Say where a 2-D point lies relative to the axes and the diagonal."""
    match point:
        case (0, 0):
            return "origin"
        case (x, 0):
            return f"on the x-axis at {x}"
        case (0, y):
            return f"on the y-axis at {y}"
        case (x, y) if x == y:
            return "on the diagonal"
        case _:
            return "elsewhere"


for point in [(0, 0), (3, 0), (0, -2), (4, 4), [5, 0], (1, 2)]:
    print(f"{str(point):>8}: {describe(point)}")
  (0, 0): origin
  (3, 0): on the x-axis at 3
 (0, -2): on the y-axis at -2
  (4, 4): on the diagonal
  [5, 0]: on the x-axis at 5
  (1, 2): elsewhere

A dictionary cannot express this. Its keys are compared by equality (and must be hashable), so it can hold an entry for (0, 0) but not one for "any point whose second coordinate is 0", it cannot hand you x or y, and it has no guards. Sequence patterns match lists as well as tuples, which is why [5, 0] lands on the x-axis. The same kind of pattern works on dataclasses (case Point(x=0, y=0):), on dictionaries such as parsed JSON (case {"type": "click", "pos": (x, y)}:) and on types (case int() | float():).

How dictionaries scale: a registry

The dictionary has one more advantage that the other two lack: it does not have to be written in one place. With a small decorator, each function can add itself to the dictionary where it is defined:

HANDLERS: dict[str, Operation] = {}


def register(name: str) -> Callable[[Operation], Operation]:
    """Return a decorator that stores a function in HANDLERS under `name`."""

    def wrap(fn: Operation) -> Operation:
        HANDLERS[name] = fn
        return fn

    return wrap


for fn in (add, subtract, multiply, divide):
    register(fn.__name__)(fn)

Writing @register("add") on the line above def add is the same as add = register("add")(add): the decorator stores the function and hands it back unchanged. Here I registered the four functions from before by calling it directly. A new option takes one decorated function and no edit anywhere else:

@register("power")
def power(a: float, b: float) -> float:
    """Return a raised to the power b."""
    return a**b


def dispatch_registry(task: str, a: float, b: float) -> float:
    """Apply the handler registered under `task` to a and b."""
    handler = HANDLERS.get(task)
    if handler is None:
        raise ValueError(f"unknown task: {task!r}; choose from {sorted(HANDLERS)}")
    return handler(a, b)


print(sorted(HANDLERS))
print(dispatch_registry("power", 3, 2))
try:
    dispatch_registry("modulo", 3, 2)
except ValueError as err:
    print(f"ValueError: {err}")
['add', 'divide', 'multiply', 'power', 'subtract']
9
ValueError: unknown task: 'modulo'; choose from ['add', 'divide', 'multiply', 'power', 'subtract']

This is how the dictionary scales in a real project: each loss, model or metric lives in its own file and registers itself, and the code that reads the config never changes. Because the registry knows its keys, the error can list the valid names. The one catch is that a function is registered only when its module is imported, so a package usually imports all of them in its __init__.py.

A machine-learning example: losses and optimisers by name

This is where I actually use the idea. A training script reads a config, and two dictionaries turn its strings into PyTorch objects. The values are classes, not functions, which works in the same way, because a class is also something you call:

import torch

LOSSES: dict[str, Callable[..., torch.nn.Module]] = {
    "mse": torch.nn.MSELoss,
    "mae": torch.nn.L1Loss,
    "huber": torch.nn.HuberLoss,
}

OPTIMISERS: dict[str, Callable[..., torch.optim.Optimizer]] = {
    "sgd": torch.optim.SGD,
    "adam": torch.optim.Adam,
    "adamw": torch.optim.AdamW,
}


def make_loss(name: str) -> torch.nn.Module:
    """Build the loss called `name` in LOSSES."""
    loss_class = LOSSES.get(name)
    if loss_class is None:
        raise ValueError(f"unknown loss: {name!r}; choose from {sorted(LOSSES)}")
    return loss_class()


def make_optimiser(name: str, params, lr: float) -> torch.optim.Optimizer:
    """Build the optimiser called `name` in OPTIMISERS for the parameters `params`."""
    optimiser_class = OPTIMISERS.get(name)
    if optimiser_class is None:
        raise ValueError(f"unknown optimiser: {name!r}; choose from {sorted(OPTIMISERS)}")
    return optimiser_class(params, lr=lr)
config = {"loss": "mse", "optimiser": "adam", "lr": 0.05}  # as read from a YAML or JSON file

torch.manual_seed(0)
x = torch.randn(64, 3)
y = x @ torch.tensor([1.0, -2.0, 0.5]) + 0.1 * torch.randn(64)
model = torch.nn.Linear(3, 1)
loss_fn = make_loss(config["loss"])
optimiser = make_optimiser(config["optimiser"], model.parameters(), lr=config["lr"])

for step in range(201):
    optimiser.zero_grad()
    loss = loss_fn(model(x).squeeze(1), y)
    loss.backward()
    optimiser.step()
    if step % 50 == 0:
        print(f"step {step:3d}: {config['loss']} loss = {loss.item():.4f}")

try:
    make_loss("cross_entropy")
except ValueError as err:
    print(f"ValueError: {err}")
step   0: mse loss = 6.5688
step  50: mse loss = 0.1307
step 100: mse loss = 0.0074
step 150: mse loss = 0.0071
step 200: mse loss = 0.0071
ValueError: unknown loss: 'cross_entropy'; choose from ['huber', 'mae', 'mse']

Changing "adam" to "sgd" in the config changes the optimiser without touching the code, and a misspelt name stops the run at once with a message that lists the valid names. The same keys can validate the config before training starts, or fill the choices of an argparse option. Which loss to choose is a separate question, which I cover in my post on loss functions for regression and classification.

Two more tools

Two more tools complete the picture. The first is the plain in operator. When several names share one branch, an if can test them all at once, and for a small set of names split into two or three groups this is often the clearest code there is:

def is_commutative(task: str) -> bool:
    """Return True if swapping a and b leaves the result of `task` unchanged."""
    if task in ("add", "multiply"):
        return True
    elif task in ("subtract", "divide"):
        return False
    raise ValueError(f"unknown task: {task!r}")


print({task: is_commutative(task) for task in TASKS})
{'add': True, 'subtract': False, 'multiply': True, 'divide': False}

match writes the same thing as an or-pattern, case "add" | "multiply":, while a dictionary needs one key per name, so grouping names is where the chain and match read better than a dictionary.

The second tool chooses a function by the type of an argument rather than by a name. functools.singledispatch turns a function into the fallback, and each register adds an implementation for one type, which it reads from the annotation of the first parameter. Here it formats values for a log line:

from functools import singledispatch

import numpy as np


@singledispatch
def fmt(value) -> str:
    """Format a value for a log line; used for any type without its own implementation."""
    return repr(value)


@fmt.register
def _(value: float) -> str:
    return f"{value:.4g}"


@fmt.register
def _(value: list) -> str:
    return "[" + ", ".join(fmt(item) for item in value) + "]"


@fmt.register
def _(value: torch.Tensor) -> str:
    return f"tensor of shape {tuple(value.shape)}"


for value in [0.123456, np.float64(2 / 3), 3, "adam", [0.5, 1 / 3], torch.zeros(2, 3)]:
    print(f"{type(value).__name__:>8}: {fmt(value)}")
   float: 0.1235
 float64: 0.6667
     int: 3
     str: 'adam'
    list: [0.5, 0.3333]
  Tensor: tensor of shape (2, 3)

Only the type of the first argument counts, and subclasses are included: NumPy's float64 is a subclass of Python's float, so it gets the float implementation, which a dictionary keyed by type(value) would miss. An int has no implementation of its own, so it falls back to repr. This is the tool for doing one job on several kinds of data; to choose between jobs by name, the dictionary is still the one. For methods, the same idea is functools.singledispatchmethod.

Testing every option

A dispatcher is a list of options, and each one can break on its own: a typo in a key, two names swapped, an option added to one dispatcher and forgotten in another. pytest.mark.parametrize turns one test function into one test per value, so every option is tested and a new option only has to be added to the list. Stacking two parametrize decorators runs every combination: here four dispatchers times four tasks gives 16 tests from one function, each checked against the operator module as an independent reference, plus one test per dispatcher for an unknown name and one for division by zero.

import pytest

ALL_DISPATCHERS = [dispatch_if, dispatch_dict, dispatch_match, dispatch_registry]


def name_of(fn: Callable) -> str:
    """Name each test after its dispatcher, as in test_matches_operator[dispatch_if-add]."""
    return fn.__name__


@pytest.mark.parametrize("task", TASKS)
@pytest.mark.parametrize("dispatch", ALL_DISPATCHERS, ids=name_of)
def test_matches_operator(dispatch, task):
    assert dispatch(task, 3.0, 2.0) == OPS[task](3.0, 2.0)


@pytest.mark.parametrize("dispatch", ALL_DISPATCHERS, ids=name_of)
def test_unknown_task_raises(dispatch):
    with pytest.raises(ValueError, match="unknown task"):
        dispatch("modulo", 3.0, 2.0)


@pytest.mark.parametrize("dispatch", ALL_DISPATCHERS, ids=name_of)
def test_divide_by_zero_raises(dispatch):
    with pytest.raises(ZeroDivisionError):
        dispatch("divide", 3.0, 0.0)

In a project these tests would sit in a file such as tests/test_dispatch.py that imports the dispatchers from their module, and running pytest in the shell would find them: it collects the functions whose names start with test_ from the files whose names start with test_. A notebook has no such file, so the folded cell below writes a temporary one that imports the three test functions, runs pytest on it and prints the report without the run time, which changes from run to run:

Show code
import contextlib
import io
import re
import tempfile
from pathlib import Path

test_names = ["test_matches_operator", "test_unknown_task_raises", "test_divide_by_zero_raises"]

with tempfile.TemporaryDirectory() as tmp:
    test_file = Path(tmp) / "test_dispatch.py"
    test_file.write_text(f"from __main__ import {', '.join(test_names)}\n")
    report = io.StringIO()
    with contextlib.redirect_stdout(report):
        exit_code = pytest.main(
            [str(test_file), "-q", "--no-header", "--color=no", "-p", "no:cacheprovider",
             "-o", "console_output_style=classic"]
        )

print(re.sub(r" in [0-9.]+s", "", report.getvalue()).strip())
assert exit_code == pytest.ExitCode.OK
........................
24 passed

Each dot is a passing test. A failure would print an F instead, followed by the id of the failing test, such as test_matches_operator[dispatch_match-divide], which names the dispatcher and the task.

Comparison

if/elif Dictionary match
Readability Clear for two or three options; repetitive after that One line per option, all in one place Clear; the subject is written once
Extensibility Edit the function for every new option Add a key from anywhere, or with a registry decorator; the keys can be listed Edit the function for every new option
Error handling Needs an explicit else: raise; without it, returns None d[task] raises KeyError; d.get(task) plus a ValueError gives a clear message that can list the valid names Needs an explicit case _: raise; without it, returns None
Speed, four options (this machine) 41 ns for the first option, 52 ns for the fourth; grows with every option 50 to 55 ns; the same dispatch cost for every option, slowest on average 43 ns for the first option, 56 ns for the fourth; grows like the chain
Can decide on Any condition: in, ranges, isinstance Exact, hashable keys only Literals, structure, types and guards, binding values to names
Python version Any Any 3.10 or newer

My recommendation: when a name maps one-to-one to a function or class, use a dictionary, and a registry once the options live in different files. That covers losses, optimisers, schedulers and metrics chosen from a config. Use match when the decision depends on the shape of the data rather than on one string: tuples, dataclasses, parsed JSON or commands. Keep if/elif for two or three options, or for conditions that are not equality, such as ranges. Whichever you choose, raise a ValueError that names the bad value, never return a string where a number belongs, and do not name your functions after built-ins.

Takeaways

  • To choose a function by name, a dictionary from names to functions (or to the operator module's functions, or to classes such as torch.nn.MSELoss) is one line per option, can list its own keys and costs the same whichever option is chosen; a decorator registry lets each option add itself from its own file. For four options all three approaches cost 41 to 56 ns a call on this machine, so choose for readability, not speed.
  • Fail loudly, and in the same way everywhere: raise ValueError(f"unknown task: {task!r}") for an unknown name and let a / b raise ZeroDivisionError. Never return a string such as "Error" or "Invalid task" where a number is expected, and never name a function after a built-in such as sum.
  • match (Python 3.10 or newer) earns its place when the decision depends on the shape of the data (tuples, dataclasses, guards), not on one string. End it with case _:, because a bare name such as default is a capture pattern that matches everything.

References

  1. Python documentation, Design and History FAQ: "Why isn't there a switch or case statement in Python?", which suggests a dictionary of functions.
  2. PEP 634: Structural Pattern Matching: Specification, PEP 635: Motivation and Rationale and PEP 636: Tutorial, 2020. match was added in Python 3.10.
  3. Python documentation, the match statement in the Language Reference, including capture and wildcard patterns.
  4. Python documentation, operator: standard operators as functions.
  5. Python documentation, timeit: measure execution time of small code snippets, whose notes explain why the fastest of several runs is the number to report.
  6. Python documentation, collections.abc.Callable and annotating callable objects.
  7. PyTorch documentation, loss functions and torch.optim.
  8. Python documentation, functools.singledispatch, and PEP 443: Single-dispatch generic functions, 2013.
  9. pytest documentation, How to parametrize fixtures and test functions.