[Python-Dev] Let's just *keep* lambda
Bengt Richter
bokr at oz.net
Thu Feb 9 19:24:43 CET 2006
On Thu, 09 Feb 2006 17:39:31 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= <martin at v.loewis.de> wrote:
>Jiwon Seo wrote:
>> Apparently, simplest example is,
>>
>> collection.visit(lambda x: print x)
>
>Ok. I remotely recall Guido suggesting that print should become
>a function.
>
Even so, that one is so trivial to define (other than the >> part):
>>> import sys
>>> def printfun(*args): sys.stdout.write(' '.join(map(str,args))+'\n')
...
>>> lamb = lambda x: printfun(x)
>>>
>>> lamb(123)
123
>>> printfun('How', 'about', 'that?')
How about that?
Also the quasi-C variant:
>>> def printf(fmt, *args): sys.stdout.write(fmt%args)
...
>>> (lambda x: printf('How about this: %s', x))('-- also a function\n(no \\n here ;-) ')
How about this: -- also a function
(no \n here ;-) >>>
>It's not a specific example though: what precise library provides
>the visit method?
>
>> which currently is not possible. Another example is,
>>
>> map(lambda x: if odd(x): return 1
>> else: return 0,
>> listOfNumbers)
>
>Hmm. What's wrong with
>
>map(odd, listOfNumbers)
>
>or, if you really need ints:
>
>map(lambda x:int(odd(x)), listOfNumbers)
>
>> Also, anything with exception handling code can't be without explicit
>> function definition.
>>
>> collection.visit(lambda x: try: foo(x); except SomeError: error("error
>> message"))
>
>That's not a specific example.
>
>>> (lambda : """
... I will say that the multi-line part
... of the argument against lambda suites
... is bogus, though ;-)
... """)(
... ).splitlines(
... )[-1].split()[1].capitalize(
... ).rstrip(',')+'! (though this is ridiculous ;-)'
'Bogus! (though this is ridiculous ;-)'
And, as you know, you can abuse the heck out of lambda (obviously this is
ridiculous**2 avoidance of external def)
>>> lamb = lambda x: eval(compile("""if 1:
... def f(x):
... try: return 'zero one two three'.split()[x]
... except Exception,e:return 'No name for %r -- %s:%s'%(x,e.__class__.__name__, e)
... """,'','exec')) or locals()['f'](x)
>>> lamb(2)
'two'
>>> lamb(0)
'zero'
>>> lamb(4)
'No name for 4 -- IndexError:list index out of range'
>>> lamb('x')
"No name for 'x' -- TypeError:list indices must be integers"
But would e.g. [1]
collection.visit(lambda x:: # double ':' to signify suite start
try: return 'zero one two three'.split()[x]
except Exception,e:return 'No name for %r -- %s:%s'%(x,e.__class__.__name__, e)
)
be so bad an "improvement"? Search your heart for the purest answer ;-)
(requires enclosing parens, and suite ends on closing ')' and if multiline,
the first line after the :: defines the indent-one left edge, and explicit
return of value required after ::).
[1] (using the function body above just as example, not saying it makes sense for collection.visit)
Regards,
Bengt Richter
More information about the Python-Dev
mailing list