The Python dictionary dispatch pattern
Published on under the VisionScript category.Toggle Memex mode
One of my favourite patterns in the Python programming language is the "dictionary dispatch" pattern. This pattern is when you have a dictionary with string keys and functions as values. These functions can then be called concisely. This is useful if you have a range of functions to which different values can be applied that all accept (around) the same arguments.
Consider this code:
math_exprs = {
"add": lambda x, y: x + y,
"subtract": lambda x, y: x - y,
"multiply": lambda x, y: x * y,
...
}
To run a math expression, I can use:
math_exprs["add"](1, 2)
math_exprs["subtract"](1, 2)
...
The API -- retrieve an item from a dictionary, then directly call the function -- is the same across all expressions. This is particularly useful when parsing user input which may need to be directed to one of many locations, or when parsing syntax trees.
Consider this dictionary, part of the VisionScript programming language:
SUPPORTED_INFERENCE_MODELS = {
"groundingdino": lambda self, classes: registry.grounding_dino_base(self, classes),
"yolov8": lambda self, classes: registry.yolov8_base(self, classes),
...
}
This dictionary maps model names to an anonymous function that calls a function in a different file. I use it to figure out what function should handle model inference for a developer. Rather than have an if statement, which would grow in size and become harder to read as I add more models to the dictionary, I can use the above dictionary dispatch pattern.
To call a model, I use:
results, inference_classes, classes = SUPPORTED_INFERENCE_MODELS[model](
self, classes
)
Here, model
is the name of the model (the key in the dictionary). I directly call the function returned by the dictionary with the brackets syntax, passing in the values it needs (in this case, self
, which contains global state for the languge, and classes
). All functions return three standard values.
I am a huge fan of this pattern. I have used it when implementing my own Lisp in Python, for mapping token types in VisionScript to their associated functions, for mapping models to the functions that handle inference for that model in VisionScript, and more.
Responses
Comment on this post
Respond to this post by sending a Webmention.
Have a comment? Email me at readers@jamesg.blog.