[Python-Dev] Adding any() and all()

Alex Martelli aleaxit at yahoo.com
Fri Mar 11 19:35:04 CET 2005


On Mar 11, 2005, at 17:28, Guido van Rossum wrote:

> PS in the blog responses, a problem with sum() was pointed out --
> unless you use the second argument, it will only work for numbers. Now

Why is that a *problem*?  It solves the "end case (if the sequence is 
empty" which you mention for any() and all() [[indeed, I think a 
similar approach to any and all might be best: have them return an item 
from the sequence, an empty sequence uses the optional second item 
defaulting to something reasonable -- 0 for sum, False for any, True 
for all, for example]] in a neatly explicit way.  As I recall, I had 
tried to handle non-empty sequences by picking the first item and doing 
following + on it (with internal implementation specialcasing for 
strings, to avoid an "attractive nuisance" situation), and you cut the 
gordian knot by pronouncing about the second argument with a default of 
0 (I immediately thought your pronouncement was excellent and I still 
can't see why it wouldn't be).

Forcing the user to provide a 2nd arg when summing a sequence of 
non-numbers (say, datetime.timedelta instances, that's one example that 
ended up in the 2nd ed Cookbook) is good because it ensures a good 
return value when the sequence is empty (say, timedelta(0) rather than 
0 as a number).

If you're considering revisions to sum's design, my suggestion would be 
to find a way to let the user tell sum to use a more accurate approach 
when summing floats.  Summing a million floats with a loop of 
total+=item loses a LOT of accuracy (several digits' worth!) -- but 
doing the summation the right way takes O(N) auxiliary temporary space, 
so both approaches (the naive, performance-optimized accuracy disaster, 
and the expensive but accurate one) should ideally be available.  An 
optional use_partials keyword argument defaulting to False, for 
example, might allow that... (again, I've hopefully clarified the 
issues in another 2nd ed Cookbook recipe, I guess I can post that if it 
helps).


Alex



More information about the Python-Dev mailing list