Switch statements again
Brian Quinlan
brian at sweetapp.com
Wed Jan 15 18:20:02 EST 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
masks = [MASK_SATURDAY, MASK_SUNDAY, ...]
if calDayOfWeekMask not in masks:
raise ValueError, 'invalid mask "%r"' % calDayOfWeekMask
dayOfWeek -= masks.index(calDayOfWeekMask)
if ...
Cheers,
Brian
More information about the Python-list
mailing list