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

Smith, Jeff jsmith at medplus.com
Mon Feb 7 15:14:55 CET 2005


Alan,

No use beating this dead horse...I guess that's why there are so many
languages in the first place.  Different people are comfortable with
different things.  (I did warn you that I like both Lisp and Prolog and
only wish I had more of a reason to use them :-)

As an aside, I did try to create a lambda based solution but was unable.
Let me know what's wrong:

ftable = { 'a' : lambda: print 'a',
           'b' : lambda: print 'b or c',
           'c' : lambda: print 'b or c',
           'd' : lambda: pass }
ftable.get(var, lambda: print 'default case')()


  File "C:\scratch\Script1.py", line 2
    ftable = { 'a' : lambda: print 'a',
                                 ^
SyntaxError: invalid syntax

Jeff

-----Original Message-----
From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] 
Sent: Friday, February 04, 2005 6:39 PM
To: Smith, Jeff; Jacob S.; Nicholas.Montpetit at deluxe.com;
tutor at python.org
Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT]


> Now who's joking?

:-)

> Are you saying that
> 
> switch var:
> case 'a':
>    print 'a'
> ...
> default:
>    print 'default case'
>
> Is less clear and maintainable than

I don;tthink I said (certainly didn't mean) less clear, but 
yes it is less maintainable.

But then...

> def do_this_function():
> print 'a'

> ....
> ftable = { 'a' : do_this_function,
>            'b' : do_that_function,
>            'c' : do_that_function,
>            'd' : do_pass_function }
> ftable.get(var, do_default_function)()

I did also say that it was best with proper lambdas

ftable = {'a' : lambda: print 'a',
          'b' : lambda: print 'b'
etc///

and I'd code the calling section:

try: ftable[value]()
except KeyError: doDefaultFunction()

Its more maintainable because even if the switches proliferates 
as they tend to do, the dictionary stays in one place and the 
calling code never needs changing. So the changes are much 
more localised. And of course the more complex the case 
actions are, the more effective the dictionary/function 
approach becomes.

Alan G.


More information about the Tutor mailing list