Message232626
from functools import reduce
def add(a,b): return a+b
reduce(add, {})
>>>
Traceback (most recent call last):
File "C:\Programs\Python34\tem.py", line 3, in <module>
reduce(add, {})
TypeError: reduce() of empty sequence with no initial value
However, the reduce-equivalent code in the doc sets a bad example and forgets to account for empty iterators.
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else: ...
So it lets the StopIteration escape (a bad practice that can silently break iterators). The code should be
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
value = next(it)
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value") from None
else: ...
(patch coming) |
|
Date |
User |
Action |
Args |
2014-12-14 00:27:27 | terry.reedy | set | recipients:
+ terry.reedy, docs@python |
2014-12-14 00:27:27 | terry.reedy | set | messageid: <1418516847.13.0.26860108886.issue23049@psf.upfronthosting.co.za> |
2014-12-14 00:27:27 | terry.reedy | link | issue23049 messages |
2014-12-14 00:27:25 | terry.reedy | create | |
|