Switch statements again

Jack Diederich jack at performancedrivers.com
Wed Jan 15 18:03:47 EST 2003


On Wed, Jan 15, 2003 at 05:46:07PM -0500, Steven Scott wrote:
> 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?"
> 
>     switch (calDayOfWeekMask)
>       {
> 	  <snip>
> 	
>       case MASK_SUNDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_MONDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_TUESDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_WEDNESDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_THURSDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_FRIDAY:
> 		dayOfWeek--;		// and fall thru
>       case MASK_SATURDAY:
> 		if (calWeekNumber == LAST)
> 		  {
> 		    occurrence.setDay(occurrence.getDaysInMonth());
> 		    occurrence.addDays(- ((7 - dayOfWeek
> 					   + occurrence.getDayOfWeek()) %
> 7));
> 		  }
> 		else
> 		  {
> 		    occurrence.setDay(1 + ((calWeekNumber - 1) * 7));
> 		    occurrence.addDays((dayOfWeek + 7 -
> occurrence.getDayOfWeek()) % 7);
> 		  }
> 		break;
> 		
>       default:
> 		return FAIL;
>       }

Assume that the mask names are like SUN .. SAT below

# setup the masks offsets
val = 6
subtract = {}
for (day_mask) in (SUN, MON, TUE, WED, THU, FRI, SAT):
  subtract[day_mask] = val
  val -= 1

try:
  dayOfWeek -= subtract[calDayOfWeekMask]
  if (calWeekNumber == LAST):
    # do one thing
  else:
    # do your other thing
except (KeyError,), e:
  return FAIL


There might be a typo, but this is close to what you want.

You could also do something fancier to initialize such as
using a list comprehension or zip().  Comprehensions always
hurt readability (ALWAYS), and we don't need the speedup
here so we do it explicitly.

-jackdied

  








More information about the Python-list mailing list