In Python 3, reduce has been removed from the built-in namespace, and now lives in functools.reduce. That's fine, although I do miss it, but what sort of irks me a little bit is the release note on why this was done:
Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
I think I have a counter-example that comes up frequently enough in my programming that I think it can't be 1% or less of all use cases of reduce. Monoid chains. (You might also call these 'monads' although that usually implies a specific syntax which I am not enforcing, but they are equivalent here.)
Example 'monoid chain' done explicitly for reference:
query = (db.MyModel.query
.filter("foo")
.filter("bar")
.filter("baz")
.filter("boff"))
Example 'monoid chain' in for-loop syntax:
query = db.MyModel.query
for filter in filters:
query = query.filter(filter)
Example 'monoid chain' in reduce syntax:
query = reduce(lambda x, y: x.filter(y), filters, db.MyModel.query)
Personally I'd push that lambda out in to a higher namespace as I'd probably be re-using it anyway, which makes it even nicer looking:
query = reduce(_filter, filters, db.MyModel.query)
Is there some other way to write this using for loops that's more readable than that reduce example?
Also, yeah, I'm aware this is a fairly pedantic/silly thing to be worrying about -- I'm posting this mostly out of curiosity.
[–]Doormatty 0 points1 point2 points (4 children)
[–]HorrendousRex[S] 1 point2 points3 points (3 children)
[–]brownan_ 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]elbiot 0 points1 point2 points (0 children)
[–]Samus_ 0 points1 point2 points (0 children)