_initial_missing = object()
-def reduce(function, sequence, initial=_initial_missing):
+def reduce(function, sequence, /, initial=_initial_missing):
"""
reduce(function, iterable, /[, initial]) -> value
return value
+try:
+ from _functools import reduce
+except ImportError:
+ pass
+
################################################################################
### partial() argument application
return val
__class_getitem__ = classmethod(GenericAlias)
-
-def _warn_python_reduce_kwargs(py_reduce):
- @wraps(py_reduce)
- def wrapper(*args, **kwargs):
- if 'function' in kwargs or 'sequence' in kwargs:
- import os
- import warnings
- warnings.warn(
- 'Calling functools.reduce with keyword arguments '
- '"function" or "sequence" '
- 'is deprecated in Python 3.14 and will be '
- 'forbidden in Python 3.16.',
- DeprecationWarning,
- skip_file_prefixes=(os.path.dirname(__file__),))
- return py_reduce(*args, **kwargs)
- return wrapper
-
-reduce = _warn_python_reduce_kwargs(reduce)
-del _warn_python_reduce_kwargs
-
-# The import of the C accelerated version of reduce() has been moved
-# here due to gh-121676. In Python 3.16, _warn_python_reduce_kwargs()
-# should be removed and the import block should be moved back right
-# after the definition of reduce().
-try:
- from _functools import reduce
-except ImportError:
- pass
self.assertRaises(TypeError, self.reduce, add, [0, 1], initial="")
self.assertEqual(self.reduce(42, "", initial="1"), "1") # func is never called with one item
+ def test_reduce_with_kwargs(self):
+ with self.assertRaises(TypeError):
+ self.reduce(function=lambda x, y: (x or 1) + y, sequence=[1, 2, 3, 4, 5])
+ with self.assertRaises(TypeError):
+ self.reduce(function=lambda x, y: x + y, sequence=[1, 2, 3, 4, 5], initial=1)
+ with self.assertRaises(TypeError):
+ self.reduce(lambda x, y: x + y, sequence=[1, 2, 3, 4, 5], initial=1)
+
@unittest.skipUnless(c_functools, 'requires the C _functools module')
class TestReduceC(TestReduce, unittest.TestCase):
class TestReducePy(TestReduce, unittest.TestCase):
reduce = staticmethod(py_functools.reduce)
- def test_reduce_with_kwargs(self):
- with self.assertWarns(DeprecationWarning):
- self.reduce(function=lambda x, y: x + y, sequence=[1, 2, 3, 4, 5], initial=1)
- with self.assertWarns(DeprecationWarning):
- self.reduce(lambda x, y: x + y, sequence=[1, 2, 3, 4, 5], initial=1)
-
class TestCmpToKey: