Friday, April 08, 2011

Python switch statement

Having a bit of fun at 3 in the morning.

The Python version of the C-style switch statement is either a bunch of if/else's or a dictionary. Going the dictionary route can be ugly looking (not to mention confusing, pulling a value out of a mapping and calling it). This just encapsulates the whole thing and adds some support for a pseudo-default case.

The structure is a bit weird, nowhere near as nice as regular syntax, but if you absolutely have to do this, it makes it easier to read.

No comments:

Post a Comment