Switch statements again

Carl Banks imbosol at vt.edu
Wed Jan 15 18:25:40 EST 2003


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?"


If you don't like the if-then-else, then you can use a dict like this:

At top level (some will not like this because it declares a global,
but I say a global is not evil as long as you promise never to change
it):

    dayOfWeekDecimation = { MASK_SUNDAY: 6,
                            MASK_MONDAY: 5,
                            MASK_TUESDAY: 4,
                            MASK_WEDNESDAY: 3,
                            MASK_THURSDAY: 2,
                            MASK_FRIDAY: 1,
                            MASK_SATURDAY: 0 }


Inside your function:

    dayOfWeek -= dayOfWeekDecimation[calDayOfWeekMask]
    if calWeekNumber == LAST:
        ... etc. ...


No need to worry about calDayOfWeek not being one of the ordained
values; Python will throw an exception if it is not.


>    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;
>      }


-- 
CARL BANKS




More information about the Python-list mailing list