Another stab at a "switch/case" construct (for Python 3000):

Cliff Wells logiplexsoftware at earthlink.net
Fri Mar 29 16:57:59 EST 2002


On Fri, 29 Mar 2002 21:11:48 -0000
Steve Lamb wrote:

> On Fri, 29 Mar 2002 10:48:15 GMT, Benjamin Schollnick
<junkster at rochester.rr.com> wrote:
> > IF X == 0:
> >    DO_THIS ()
> > ELIF X == 2:
> >    DO_THIS (2)
> > ELIF X == 4:
> >    DO_THIS (X+2)
> > ELIF Y == 6:
> >    DO_THIS()
> > ELIF Z == "ZEBRA":
> >    DO_THIS ( ZEBRA )
> > ELSE:
> >    DO_NOT_DO_THIS ()
>  
>  
> > But, this routine is not exactly readable compared to a case:
>  
> > CASE X of:
> >    0  : DO_THIS()
> >    2  : DO_THIS (2)
> >    4  : DO_THIS (x+2)
> >    6  : DO_THIS ()
> >  ELSE:
> >       DO_NOT_DO_THIS()
> 
> its_called_a_directory_pointing_to_functions = {'case':closed}
> 
>     I do not believe that any language which can have a hash of function
> pointers has any business with a case statement.

The case statement is definitely cleaner than the if/elif/else construct. 
I'd have to agree with Steve Lamb that you can use hash pointers, so you
could also do (lambdas necessary to duplicate above case statement):

{ # case x of
    0: lambda x: do_this(),
    2: lambda x: do_this(2),
    4: lambda x: do_this(x + 2),
    6: lambda x: do_this(),
}.get(x, lambda x: do_not_do_this())(x)

But I'm not sure that this is very clear code (at least not at first
glance).  I don't feel that passionate either way on the subject.  Probably
having a case statement would make some things clearer but might also
encourage less though out approaches to problems.  Situations where you
must test for many individual values are usually an indication that your
solution isn't general enough.

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




More information about the Python-list mailing list