Switch statements again

Brian Quinlan brian at sweetapp.com
Thu Jan 16 00:20:02 CET 2003

> I've been reading the claims about doing things a more elegant way in
> python when it comes to switch statements, using if-elif-else 
> and/or dictionaries of function pointers.  the following can be 
> done with if-elif-else (and that's how I did it), but it sure is ugly.

> my question is simply "what's the best way to do this in python?"

I don't understand the problem fully (if I did, I might use a list
instead of a dictionary) but:

masks = {MASK_SATURDAY : 0, MASK_SUNDAY : 1, MASK_MONDAY : 2, ...}

if not masks.has_key[calDayOfWeekMask]
     raise ValueError, 'invalid mask "%r"' % calDayOfWeekMask
dayOfWeek -= marks[calDayOfWeekMask]
if ...

The list solution would look like

if calDayOfWeekMask not in masks:
     raise ValueError, 'invalid mask "%r"' % calDayOfWeekMask

dayOfWeek -= masks.index(calDayOfWeekMask)
if ...


More information about the Python-list mailing list