Given that itertools.starmap exists in the standard library, should iterools.starfilter and functools.starreduce also exist?
I appreciate that not every 5-line function should be implemented in the standard library, which is why the docs for itertools has a large collection of “recipes” at the bottom, but having a “star” version of map but not its functional-programming partners filter and reduce feels inconsistent.
I’m a big fan of starmap because is allows expressive variable names in multiple-argument lambdas, rather than having to index a tuple. Both starfilter and starreduce would bring this same benefit.
starfilter
starfilter would essentially be equivalent to
def starfilter(function, iterable):
for args in iterable:
if function(*args):
yield args
so that instead of:
filter(lambda x: x[0] * x[1] > 5, [(1,0), (5,6), (8,9)])
you could write:
starfilter(lambda x, y: x * y > 5, [(1,0), (5,6), (8,9)])
both resulting in an iterator yielding these tuples(5, 6), (8, 9)
starreduce
starreduce would essentially be equivalent to
initial_missing = object()
def starreduce(function, iterable, initial=initial_missing, /):
it = iter(iterable)
if initial is initial_missing:
value = next(it)
else:
value = initial
for element in it:
value = function(value, *element)
return value
so that instead of:
reduce(lambda acc, x: acc * x[0] + x[1], [(1,0), (5,6), (8,9)], 9)
you could write:
starreduce(lambda acc, x, y: acc * x + y, [(1,0), (5,6), (8,9)], 9)
both with a result of 417.
Or just as an additional “recipe” in the docs?
Failing support for their inclusion in the standard library - do they deserve to be included as “recipes” in the docs?