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@python components: Documentation, Interpreter Core messages: 232626 nosy: docs@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 <rep...@bugs.python.org> <http://bugs.python.org/issue23049> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com