[New-bugs-announce] [issue23049] Fix functools.reduce code equivalent.
Terry J. Reedy
report at bugs.python.org
Sun Dec 14 01:27:27 CET 2014
New submission from Terry J. Reedy:
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)
----------
assignee: docs at python
components: Documentation, Interpreter Core
messages: 232626
nosy: docs at python, terry.reedy
priority: normal
severity: normal
stage: needs patch
status: open
title: Fix functools.reduce code equivalent.
type: behavior
versions: Python 3.4, Python 3.5
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23049>
_______________________________________
More information about the New-bugs-announce
mailing list