Smith, Jeff wrote:

Jeff,

It looks like that finally is the simplest expression of the original
switch statement:

import sys
def p():
    pass
ftable = { 'a' : lambda: sys.stdout.write('a\n'),
           'b' : lambda: sys.stdout.write('b or c\n'),
           'c' : lambda: sys.stdout.write('b or c\n'),
           'd' : p }
ftable.get(var, lambda: sys.stdout.write('default case\n'))()

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 :-)

I wasn't following this thread all the way through, but to be honest, I'd have solved this differently -- that may be the best "direct translation" of some switch statement, but that doesn't mean it's the best-fit solution here. ISTM that, given the desire to print some text (or nothing) based on the contents of a variable, I would *not* handle the output inside the "switch" -- that is, I'd (conditionally) print a value from a string-containing dictionary, rather than use a table of functions that print strings.

table = { 'a': 'a', 'b': 'b or c', 'c': 'b or c', 'd': None }
result = table.get(var, 'default case')
if result:
    print result

This, to my mind, is much cleaner -- you're factoring out the repeated
code, whether print statement or call to sys.stdout.write(), reducing
the complexity of the dict.  You're making flow control much more
straightforward.  You're making the whole thing easier to read.

The key, here, is that instead of saying "I want a switch, how can I
implement that in Python?", I've taken the approach of "The end result
I want is ***; what tools does Python offer to achieve that?"  This
conceptual shift is, IMHO, *the* most important mental hurdle in
learning a [second/third/n-th] language.

Jeff Shannon
Technician/Programmer
Credit International




_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to