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

Smith, Jeff jsmith at medplus.com
Tue Feb 8 14:42:54 CET 2005


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

import sys
def p():
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 :-)


-----Original Message-----
From: Jeff Shannon [mailto:jeff at ccvcorp.com] 
Sent: Monday, February 07, 2005 9:19 PM
To: tutor at python.org
Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

Alan Gauld wrote:

>>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',
>>SyntaxError: invalid syntax
> I did say "if Python had *proper* lambdas..."
> Unfortunately Python insists on only having *expressions* as lambdas 
> and since print is a command not a function you can't use it in Python

> lambdas! Dumb or what??!
> So you are stuck with predefining a bunch of one liner functions and 
> then creating a dictionary or going back to if/elif chains, which is 
> where we came in... :-)

Well, in this particular case, if one really wants to use lambdas then 
one could (after importing sys, of course) replace the print statement 
with a call to sys.stdout.write() --

     ftable = { 'a': lambda: sys.stdout.write('a\n'), ... }

Note that sys.stdout.write() will *not* automatically add the newline 
that print does (which is why I've specified it in the above sample). 
  Indeed, print can do all sorts of odd things with whitespace, 
leaving sys.stdout.write() as the best way to have real control over 
your output anyhow...

Jeff Shannon
Credit International

Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list