I'm coming from Tcl-world ...

Tim Daneliuk tundra at tundraware.com
Fri Aug 2 17:40:03 CEST 2002


Cameron Laird wrote:
> In article <slrnakl3mb.c05.Andreas.Leitgeb at pc7499.gud.siemens.at>,
> Andreas Leitgeb <avl at logic.at> wrote:
> 			.
> 			.
> 			.
> 
>>2.) A 'switch'-thing: like a big if-elif-elif-elif-...-else but which
>>  evaluates its expression only once ... and then does all the comparisons.
> 
> 			.
> 			.
> 			.
> You're far from the first to ask about it.  I
> confess I occasionally ache from its absence.
> 
> The Python attitude, though, is that a LOT of
> switches are bogus; they're better handled as
> type resolution (switching between what amount
> to different classes) or dictionary look-up.

Python *does* have this ability, it just isn't called a "case" - it's
a *dictionary* lookup.  Suppose you want to switch on the values 1, 2, and
3, and have them return, "red", "green", and "blue".  Here is a case-like
approach implemented in Python:


def case1():
     print "red"

def case2():
     print "green"

def case3():
     print "blue"

switch-table={}
switch-table[1]=case1
switch-table[2]=case2
switch-table[3]=case3

... do something to get the the value to switch on into, say, a variable called 'SwiTch'

# Here is your whole switch/case implementation as a one-liner

switch-table[SwiTch]()


Python's beauty is that you can use this sort of thing to "switch" on pretty much
*anything", not just an integer like in C, because the index into a dictionary can
be an integer, string, or pretty much *any* object.

My quick-n-dirty budgeting program (which is more a Python tutorial than
a really useful application) makes extensive use of this sort of thing
to implement a table-driven command interpreter.  Here the "switch" is on
user input.  If interested, have a look at:

       http://www.tundraware.com/Software/hb/

-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com




More information about the Python-list mailing list