[Tutor] Are you allowed to shoot camels? [kinda OT]

Alan Gauld alan.gauld at freenet.co.uk
Tue Feb 8 22:51:51 CET 2005


As one last option... (And I confess I've kind of got off the
original thread here, this is just catching my interest now! :-)

try:
   ftable =  { 'a' : lambda: 'a',
               'b' : lambda: 'b or c',
               'c' : lambda: 'b or c' }
   print ftable[var]
except KeyError: pass

Which is actually how I would probably code it if I wqs using
a dictionary (well actually I'd miss out the lambdas in this
case, but let's imagine we are doing something just a tad
more exciting!)

Using the get() method actrually makes it more complex in this case.
But if we really do want a specific 'd' that does nothing (or more
specifically a default that does *something*, then we are back to
that bad ol' def p() again.)

Now lets look at a putative switch version:

switch var:
    case 'a' : print 'a'
    case 'b' :
    case 'c' : print 'b or c'
    else     : pass

It is one line less, but is not reusable, so if the switch needs
to be used more than once - as is often the case in label printing
scenarios particularly - the dictionary wins. But for a one-off
the switch wins. The switch also, by using drop through has the
advantage of only a single message for 'b or c' - a maintenance
win. (But that can be ameliorated by having the messages in a
separate table someplace - which is good practice anyhow for
multi lingual code.)

The final option is the if/elif option:

if var == 'a': print 'a'
elif var == 'b' or var == 'c': print 'b or c'

Which is the shortest of all of them and for simple
label printing is probably the best option too!
But once the number of cases increases, performance
starts to wane and we go back to a dictionary or our
missing switch...

What does all of this tell us?
Probably only that the old adage KISS is right:
Keep It Simple Stupid!

:-)

> I do note that it took this group of experienced programmers several
> tries to impliment this simple switch statement without actually
using
> switch.  I dare say with standard switch syntax we would've had it
right
> the first time :-)

Oh I dunno, I've seen some pretty weird switch code.
But if the switch didn't allow drop through it might've
worked first time ;-)

Alan G.



More information about the Tutor mailing list