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

Jeff Shannon jeff at ccvcorp.com
Tue Feb 8 03:18:40 CET 2005


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
Technician/Programmer
Credit International





More information about the Tutor mailing list