reduce()--what is it good for?

Alex Martelli aleaxit at yahoo.com
Sat Nov 8 12:24:03 EST 2003


Anton Vredegoor wrote:

> anton at vredegoor.doge.nl (Anton Vredegoor) wrote:
> 
>>    def factorial(x):
>>        b = _Memo.biggest
>>        if x > b: return reduce(mymul, xrange(b+1,x+1), b)
>>        return _Memo.facdict[x]
> 
> Sorry, this part should be:
> 
>     def factorial(x):
>         b = _Memo.biggest
>         if x > b:
>             start = _Memo.facdict[b]
>             return reduce(mymul, xrange(b+1,x+1), start)
>         return _Memo.facdict[x]

The horrid complication of this example -- including the global side 
effects, and the trickiness that made even you, its author, fall into such 
a horrid bug -- is, I think, a _great_ testimonial to why reduce should go.
I would also include in this harrowing complexity the utter frailty of the
(textually separated) _Memo / mymul coupling, needed to maintain
_Memo's unstated invariant.  This code is as close to unmaintainable,
due to complexity and brittleness, as Python will allow.

I will gladly concede that reduce IS hard to beat if your purpose is to
write complex, brittle, hard-to-maintain code.

Which is exactly why I'll be enormously glad to see the back of it, come
3.0 time, and in the meantime I heartily suggest to all readers that (like,
say, apply) it is best (_way_ best) avoided in all new code.


Alex





More information about the Python-list mailing list