Python Dispatch Table with Operator Functions

Instead of choosing which #Python function to run with if/elif/else, use a dispatch table — a dict with functions as values: from operator import add, sub, mul ops = {'+':add, '-':sub, '*':mul} s = input('Enter +, -, or * : ') r = ops[s](10, 20) print(f'10 {s} 20 = {r}')

  • No alternative text description for this image

Be aware that Python has a match keyword, which behaves similarly to a switch case in other languages. Using a dictionary as a sudo switch case is fine, too. Technically speaking, you could replace any if/else statement with a tuple of two and then index using the outcome of a boolean expression, kinda like a rearranged ternary expression, though that can quickly run into readability issues if you try and make a sudo if/else ladder out of it.

My question is why? Is there a performance benefit or is this just about the smallest ode?

Why not s = input('Enter +, -, or * : ') r = eval(f'10 {s} 20') print(f'10 {s} 20 = {r}') ?

Reuven Lerner Ok, this is a serious question... What did Claude or your favorite LLM used in programming have to say about this. I mean if you put together a spec for a program... what do you get back? If/then/else? Or a dispatch table?

Reuven Lerner there is no universe in which this is more readable and clear than a switch or if clause.

Reminiscent of finite state machines (FSMs), typically done with a 2d array of states and events, with a function returned. In this example, there's one state and 3 different events. A lovely pattern back in the day, enabled sophisticated behaviour from highly understandable code, especially if you passed a context as the first parameter to each function (a forerunner of oop in one sense) I used to code telecoms layers using this approach

Like
Reply

Think of using a fallback, ops.get(s, lambda x, y: -1)(10,20) to handle incorrect operation entered by the user Great pattern btw

Dispatch tables are an ok way to make Python a bit more expressive. I find my self using the pattern when I come back to python from a more expresive language with proper pattern matching.

Pretty interesting, i saw a commnet talking about wrong operations for thst you could use a switch case with the supoorted ones or even an if statement to error out not supported operators

See more comments

To view or add a comment, sign in

Explore content categories