So, Rob Malda (aka CmdrTaco) of Slashdot fame spoke here last night, which was interesting. It wasn't a big event, but the number of available seats in the room was in the single-digits. Some parts of the presentation were boring, but by the end the atmosphere was more interactive and casual. Anyway, on to the topic at hand.

Early yesterday morning I posted a recipe for a new way of making readable 'switch' constructions in the Python Cookbook. (For those not in the know, Python lacks a switch/case construct.) I also brought it up in the 'switch' statement discussion on python.devel, and between these two sources it eventually made its way to Daily Python-URL and comp.lang.python through other means. It seems to have been well-received among fellow Pythonistas compared to other alternatives, the most popular (before this point) being conditions used as keys in a dictionary where the values are lambdas (or named functions) containing the appropriate case suite. While that solution is clever, it's absolutely hideous in practice (even just to describe, as you can see). I listed all known alternatives in the discussion of the recipe itself, and someone posted a comment with an Exception-based solution as well.

The method employed in my recipe allows for syntax like:


# v is the 'switched' variable
for case in switch(v):
    if case(1):
        ...
        break # just like the real thing!
    if case('two'):
        ...
        # no break, fall-through works!
    if case(100):
        ...
        break
    if case(): # used in place of 'default'
        ...

Another novel method I tested, but quickly discarded, was to use switch.__call__ in place of switch.match, which would allow for syntax like:


# v is the 'switched' variable
case = switch(v)
if case(1):
    ...
if case(2):
    ....

This saves some typing and indentation, but isn't nearly as readable in my opinion. The indentation doesn't match C's 'switch' construction, you can't use 'break' (although you could make a switch.exit function to use in place), and assignment is much less clear than the 'for ... in' construct used in the real recipe (even if neither adhere to semantic usage).

People generally have fun mucking around in Python, so I thought I'd post this little thought process on the heels of the recipe's introduction...

Oh yeah — I've got a new (Python) project up my sleeves, and it's turning out to be my best (and most marketable) one yet! Made a proof-of-concept last weekend, so I'm now in the process of refactoring the prototype code for deployment.