Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions
Peter Otten
__peter__ at web.de
Thu Jun 30 04:41:09 EDT 2016
Lawrence D’Oliveiro wrote:
> On Thursday, June 30, 2016 at 7:26:01 PM UTC+12, Peter Otten wrote:
>> foo = lambda <args>: <expr>
>>
>> there is syntactic sugar in Python that allows you to write it as
>>
>> def foo(<args>):
>> return <expr>
>>
>> with the nice side effects that it improves the readability of tracebacks
>> and allows you to provide a docstring.
>
> True, but then again the original had three lambdas, so one line would
> have to become at least 3×2 = 6 lines, more if you want docstrings.
>
>> def reduce(items, func=lambda x, y: x + y): ...
>
> There was a reason why “reduce” was removed from being a builtin function
> in Python 2.x, to being banished to functools in Python 3.
You do understand what an example is?
>> the alternative
>>
>> def reduce(items, func=add): ...
>>
>> looks more readable in my eyes even though somewhere ...
>
> Just use “sum” in this case.
Nah, the implementation is of course
def reduce(items, func=lambda x, y: x + y):
"""
>>> list(reduce([1,2,3]))
[1, 3, 6]
>>> list(reduce([42]))
[42]
>>> reduce([])
Traceback (most recent call last):
...
TypeError: reduce() with empty sequence
"""
items = iter(items)
try:
first = next(items)
except StopIteration:
raise TypeError("reduce() with empty sequence")
def _reduce(accu=first):
for item in items:
yield accu
accu = func(accu, item)
yield accu
return _reduce()
Yes, I'm kidding...
More information about the Python-list
mailing list