Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: I guess that leaves Alex's question of whether or not supplying a string of some description as the initial value can be legitimately translated to: if isinstance(initial, basestring): return initial + type(initial)().join(seq) If you're trying to get people in the habit of writing sum(x, ) instead of .join(x), I fear that they'll try sum(x, ) instead of .join(x), and be sadly disappointed. That works for me as a reason not to provide this feature. It's somewhat heartening when discussions like this turn out to show that the original design was right after all :) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: 2. How would the initial value that forms the basis of summation be built for non-empty sequences? Here's you're way off. There's never any use of +=, so never any need to create a new object. The algorithm I had in mind was: - if empty, return 2nd arg - if one item, return that - if more than one item (A, B, C, ...) return (...((A + B) + C) + ...) There I go again, missing the obvious and thinking things are more complicated than they really are. . . But I'm not so sure now. Thinking ahead to generic types, I'd like the full signature to be: def sum(seq: sequence[T], initial: T = 0) - T. and that's exactly what it is today. Conclusion: sum() is perfect after all! So the official verdict is sum() is mainly intended for numbers, but can be used with other types by supplying a default argument? I guess that leaves Alex's question of whether or not supplying a string of some description as the initial value can be legitimately translated to: if isinstance(initial, basestring): return initial + type(initial)().join(seq) rather than raising the current TypeError that suggests the programmer may want to rewrite their code. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Tue, 15 Mar 2005 07:47:20 -0800, Guido van Rossum [EMAIL PROTECTED] wrote: But I'm not so sure now. Thinking ahead to generic types, I'd like the full signature to be: def sum(seq: sequence[T], initial: T = 0) - T. Would this _syntax_ work with generic types: def sum(seq: sequence[T], initial: T = T()) - T. Cheers, Michael ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Thinking ahead to generic types, I'd like the full signature to be: def sum(seq: sequence[T], initial: T = 0) - T. Would this _syntax_ work with generic types: def sum(seq: sequence[T], initial: T = T()) - T. Maybe, but it would preclude union types; continuing with the (bad) example of strings, what should one choose for T when seq == ['a', u'b']? The general case is a sequence of objects of different types that are mutually addable. This can be made to work with the (hypothetical) type system by using unions, but you can't instantiate an instance of a union without being more specific. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Tim Peters wrote: I can't say it bothers me to specify an appropriate identity element when 0 is inappropriate. Maybe instead of a single sum() function, each summable type should have a sum() static method which uses an identity appropriate to that type. So to sum a list of integers you would use int.sum(x), to sum floats you would use float.sum(x), and to sum timedeltas you would use timedelta.sum(x). This would also neatly solve the problem of people trying to sum strings, because there would be no str.sum() method. Or alternatively, there could be a str.sum(x) which was equivalent to .join(x). Although it might be better to call it str.concat() instead of str.sum(). -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
John Williams wrote: Michael Walter wrote: Would this _syntax_ work with generic types: def sum(seq: sequence[T], initial: T = T()) - T. This doesn't make sense with existing semantics because default arguments are evaluated when the function is defined, but T() can't be evaluated until the function is called. Not to mention that if the seq is empty, there's no way of knowing what T to instantiate... -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Wed, 16 Mar 2005 08:28:22 -0800, Guido van Rossum [EMAIL PROTECTED] wrote: Thinking ahead to generic types, I'd like the full signature to be: def sum(seq: sequence[T], initial: T = 0) - T. Would this _syntax_ work with generic types: def sum(seq: sequence[T], initial: T = T()) - T. Maybe, but it would preclude union types; continuing with the (bad) example of strings, what should one choose for T when seq == ['a', u'b']? The general case is a sequence of objects of different types that are mutually addable. This can be made to work with the (hypothetical) type system by using unions, but you can't instantiate an instance of a union without being more specific. Continuing that hypothetical thought, it would be perfectly acceptable to make require an argument for union types T. Maybe T() should only be valid for non-union types. Several questions like when should T() be evaluated [1], how can we avoid ': T = T()' leading to a type error and how about optional parameters in front of ': T = T()' just popped up in my mind. Michael [1] Thanks, John! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: On Tue, 15 Mar 2005 00:05:32 +1000, Nick Coghlan [EMAIL PROTECTED] wrote: ... try: ... value += first ... except TypeError: ... raise TypeError(Cannot add first element %r to initial value %r % (first, value)) No, no, no! NO! Never catch a general exception like that and replace it with one of your own. That can cause hours of debugging pain later on when the type error is deep down in the bowels of the += operation (or perhaps deep down inside something *it* invoked). Ouch. Obviously, I hadn't thought about that. . . Wasn't there a concept floating around some time ago to support exception chaining, so additional context information could be added to a thrown exception, without losing the location of the original problem? Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Two questions about this: 1. When omitting the second argument, would supplying an empty list return 0, None or raise an exception? The last seems most reasonable, as otherwise the function is guessing about what the programmer wants. 2. How would the initial value that forms the basis of summation be built for non-empty sequences? The first element can't be used directly, as that would mutate the first element for a sequence of lists or other mutable objects. Using the default constructor for the type of the first element in the iterable has its own problem. With the second argument being ignored for non-empty iterables, it makes it impossible to use sum() with classes that do have an additive identity, but it isn't created by the default constructor. At the moment, such classes can be used by supplying the additive identity as the second argument to sum(). Both of the above cases can be supported by an approach that says: a. If a second argument is not supplied, and the iterable is empty, raise an exception. b. If a second argument is not supplied, and the iterable is not empty, use the default constructor of the type of the first argument as the initial value c. If a second argument is supplied, and the iterable is empty, return the second argument. d. If a second argument is supplied, and the iterable is not empty, use the second argument as the initial value. This scheme can be made backwards compatible with the current sum() by switching point a. from 'raise an exception' to 'return zero'. With the above compatibility change, getting all the way back to the existing sum() behaviour only requires changing point b. to say use zero as the initial value Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Tue, 15 Mar 2005 22:21:07 +1000, Nick Coghlan [EMAIL PROTECTED] wrote: Guido van Rossum wrote: I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Two questions about this: 1. When omitting the second argument, would supplying an empty list return 0, None or raise an exception? Good question... The last seems most reasonable, as otherwise the function is guessing about what the programmer wants. OTOH 0 is more compatible and None is a strong candidate too... 2. How would the initial value that forms the basis of summation be built for non-empty sequences? Here's you're way off. There's never any use of +=, so never any need to create a new object. The algorithm I had in mind was: - if empty, return 2nd arg - if one item, return that - if more than one item (A, B, C, ...) return (...((A + B) + C) + ...) But I'm not so sure now. Thinking ahead to generic types, I'd like the full signature to be: def sum(seq: sequence[T], initial: T = 0) - T. and that's exactly what it is today. Conclusion: sum() is perfect after all! -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Rationale for sum()'s design?
Title: RE: [Python-Dev] Rationale for sum()'s design? [Guido van Rossum] #- 1. When omitting the second argument, would supplying an #- empty list return 0, #- None or raise an exception? #- #- Good question... I'd go for None: - Is a good default for a non-existing argument. - If won't get None from sum() in other case (unless you do sum(None), but you should be aware of that). . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mon, 14 Mar 2005 17:57:42 -0800, Guido van Rossum [EMAIL PROTECTED] wrote: Unfortunately this started when I claimed in my blog that sum() was a replacement for 80% of all reduce() uses. That's probably where the error lies, then. When it was introduced, sum() was for summing numbers. Whether summing numbers is 80% of all uses of reduce or not is debatable, but I can't say I care. But I *do* care that this claim was taken as meaning that sum() was *intended* specifically to replace 80% of all reduce() uses - a clear misinterpretation. I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. It seems wrong to be talking about fixing sum so soon after it was introduced. Paul. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
[Guido] Unfortunately this started when I claimed in my blog that sum() was a replacement for 80% of all reduce() uses. [Paul] That's probably where the error lies, then. When it was introduced, sum() was for summing numbers. Um, Python doesn't provide a lot of special support for numbers apart from literals -- sum() should support everything that supports the + operator, just like min() and max() support everything that supports comparison, etc. Whether summing numbers is 80% of all uses of reduce or not is debatable, but I can't say I care. But I *do* care that this claim was taken as meaning that sum() was *intended* specifically to replace 80% of all reduce() uses - a clear misinterpretation. Not intended, but it happens to address many cases. I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. It seems wrong to be talking about fixing sum so soon after it was introduced. 3.0 is soon?!? -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Rationale for sum()'s design?
Title: RE: [Python-Dev] Rationale for sum()'s design? [Guido van Rossum] #- 3.0 is soon?!? *You* should answer this, ;) . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
[Guido van Rossum] Um, Python doesn't provide a lot of special support for numbers apart from literals -- sum() should support everything that supports the + operator, just like min() and max() support everything that supports comparison, etc. The discussion in the patch that introduced it may be illuminating: http://www.python.org/sf/724936 From your (Guido's) first comment there, it seems clear that sum() was originally intended only for numbers. Then it got generalized. Then sequences of strings specifically were disallowed. Then it was suggested that mention of a sequence of lists or tuples be removed from the docs, and that datetime.timedelta() be used in examples where 0 didn't make sense as the identity. Then Alex changed it to disallow any sequence of sequences. Then you suggested either specifically disallowing only sequences of lists, tuples or strings (but allowing all other sequence types as elements), _or_ going back to disallowing only sequences of strings. Alex took the latter suggestion, and that's where it ended. The closest thing to a design rationale I found is Guido's Pronouncement here, and I think it covers most issues raised this time around: http://mail.python.org/pipermail/python-dev/2003-April/034853.html The optional argument was my fault. The rest was Guido's wink: If we add an optional argument for Tim's use case, it could be used in two different ways: (1) only when the sequence is empty, (2) always used as a starting point. IMO (2) is more useful and more consistent. Nobody opposed that. I remember silently agreeing at the time, just because #2 had precedent in other languages, and seemed easiest to explain: sum(seq, start=0) same-as start + seq[0] + seq[1] + ... ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mar 15, 2005, at 01:16, Tim Peters wrote: [Eric Nieuwland] Perhaps the second argument should not be optional to emphasise this. After all, there's much more to sum() than numbers. [Greg Ewing] I think practicality beats purity here. Using it on numbers is surely an extremely common case. I'd personally be delighted if sum() never worked on anything other than numbers. That makes it easy to understand, easy to document, easy to remember, obvious at first sight, and straightforward to implement. Everything a framework isn't, but it's not a bad thing to have *something* that actually means exactly what it looks like it says 0.5 wink. I'm reasonably often using sum on lists of datetime.timedelta instances, durations, which ARE summable just like numbers even though they aren't numbers. I believe everything else for which I've used sum in production code DOES come under the general concept of numbers, in particular X+0 == X. Unfortunately, this equation doesn't hold when X is a timedelta, as X+0 raises an exception then. Alex ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
[Alex Martelli] I'm reasonably often using sum on lists of datetime.timedelta instances, durations, which ARE summable just like numbers even though they aren't numbers. I believe everything else for which I've used sum in production code DOES come under the general concept of numbers, in particular X+0 == X. Unfortunately, this equation doesn't hold when X is a tiwmedelta, as X+0 raises an exception then. I count timedeltas as numbers too -- or at least I did when sum() was being designed, cuz I asked for the optional start= argument, and precisely in order to sum things like this (timedelta was indeed the driving example at the time). I can't say it bothers me to specify an appropriate identity element when 0 is inappropriate. If it switched to ignoring the start= argument unless the sequence was empty, that would be OK too, although I think sum(seq, start=0) same-as start + seq[0] + seq[1] + ... will always be easiest to explain, so all else being equal I prefer current behavior. The number of times I've passed a sequence to sum() with elements that were lists, tuples, or any other kind of object with a concatenate meaning for __add__ is zero so far. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: But I think the logical consequence of your approach would be that sum([]) should raise an exception rather than return 0, which would be backwards incompatible. Because if the identity element has a default value, the default value should be used exactly as if it were specified explicitly. Unfortunately my proposal is also backwards incompatible, since currently sum([1,1], 40) equals 42. Somewhat ugly, but backwards compatible: sentinel = object() def sum(iterable, initial=sentinel): itr = iter(iterable) if initial is not sentinel: # Initial value provided, so use it value = initial else: try: first = itr.next() except StopIteration: # Empty iterable, return 0 for backwards compatibility # Also correct for standard numerical use return 0 # Assume default constructor returns the additive identity value = type(first)() value += first # Add the elements for item in itr: value += item return value Py sum([]) 0 Py seq = ([1], [2], [3]) Py sum(seq) [1, 2, 3] Py seq ([1], [2], [3]) Py seq = ('1', '2', '3') Py sum(seq) '123' Py seq ('1', '2', '3') Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mar 14, 2005, at 11:20, Nick Coghlan wrote: ... Somewhat ugly, but backwards compatible: I realize you're mostly talking semantics, not implementation, but, as long as we're at it, could we pretty please have back the optimization indicated by...: # Add the elements if isinstance(value, basestring): return value + ''.join(itr) for item in itr: value += item return value ...? This doesn't break bw compat since currently when value's a string sum would raise an exception... Alex ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Alex Martelli wrote: On Mar 14, 2005, at 11:20, Nick Coghlan wrote: ... Somewhat ugly, but backwards compatible: I realize you're mostly talking semantics, not implementation, but, as long as we're at it, could we pretty please have back the optimization indicated by...: It turns out the sentinel value isn't really needed either: def sum(*args): itr = iter(args[0]) try: value = args[1] except IndexError: # No start value, so use the type of the first element try: first = itr.next() except StopIteration: # Empty iterable, return 0 for backwards compatibility # When summing over something other than a sequence of # numbers, giving an initial value is a good idea. return 0 # Use default constructor to get initial value value = type(first)() value += first # Special case optimisation of strings if isinstance(value, basestring): # Rely on ''.join promoting to unicode if needed return value + ''.join(itr) # Add the elements for item in itr: value += item return value I'm not sure how much we really gain though - at the moment, using sum() for anything other than numbers gives an immediate exception. With the behaviour above, it appears to work, but will return 0 for an empty sequence instead of the additive identity of the desired type (e.g. or []). So the error will turn up somewhere else, instead of as an explicit exception at the point of origin. Maybe what we really should be doing is trapping the TypeError, and generating a more meaningful error message. E.g. Py def sum(seq, initial=0): ... itr = iter(seq) ... try: ... first = itr.next() ... except StopIteration: ... return 0 ... value = initial ... try: ... value += first ... except TypeError: ... raise TypeError(Cannot add first element %r to initial value %r % (fir st, value)) ... for item in itr: ... value += item ... return value ... Py seq = ([1], [2], [3]) Py sum(seq) Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 11, in sum TypeError: Cannot add first element [1] to initial value 0 Py sum(seq, []) [1, 2, 3] Py seq = ('1', '2', '3') Py sum(seq) Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 11, in sum TypeError: Cannot add first element '1' to initial value 0 Py sum(seq, '') '123' -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Tue, 15 Mar 2005 00:05:32 +1000, Nick Coghlan [EMAIL PROTECTED] wrote: [...] Maybe what we really should be doing is trapping the TypeError, and generating a more meaningful error message. E.g. [...] ... try: ... value += first ... except TypeError: ... raise TypeError(Cannot add first element %r to initial value %r % (first, value)) No, no, no! NO! Never catch a general exception like that and replace it with one of your own. That can cause hours of debugging pain later on when the type error is deep down in the bowels of the += operation (or perhaps deep down inside something *it* invoked). -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: But I think the logical consequence of your approach would be that sum([]) should raise an exception rather than return 0, which would be backwards incompatible. Because if the identity element has a default value, the default value should be used exactly as if it were specified explicitly. In that case I would argue in favour of keeping it the way it is, since... currently sum([1,1], 40) equals 42. ...seems quite reasonable to me. Or at least as reasonable as anything else. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Eric Nieuwland wrote: Perhaps the second argument should not be optional to emphasise this. After all, there's much more to sum() than numbers. I think practicality beats purity here. Using it on numbers is surely an extremely common case. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
On Mon, 14 Mar 2005 19:16:22 -0500, Tim Peters [EMAIL PROTECTED] wrote: [Eric Nieuwland] Perhaps the second argument should not be optional to emphasise this. After all, there's much more to sum() than numbers. [Greg Ewing] I think practicality beats purity here. Using it on numbers is surely an extremely common case. [Tim Peters] I'd personally be delighted if sum() never worked on anything other than numbers. That makes it easy to understand, easy to document, easy to remember, obvious at first sight, and straightforward to implement. Everything a framework isn't, but it's not a bad thing to have *something* that actually means exactly what it looks like it says 0.5 wink. Unfortunately this started when I claimed in my blog that sum() was a replacement for 80% of all reduce() uses. This was countered by someone who pointed out that without a 2nd argument it doesn't work for non-numbers that happen to implement __add__, and I'm not sure he was aware you could make it work *with* a 2nd argument (I know *I* had forgotten all about that :-). I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Alex's use case for a nonzero 2nd argument: total = 0 for lst in sequence_of_lists: total = sum(lst, total) can be just as easily written like this: total = 0 for lst in sequence_of_lists: total += sum(lst) and I think that's actually clearer (since the reader doesn't have to know about the 2nd argument's meaning). -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: I think the conclusion should be that sum() is sufficiently constrained by backwards compatibility to make fixing it impossible before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is only used for empty lists. Which is not unlike the get() method of dicts. So may be the default should be None? ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
Guido van Rossum wrote: - the identity (defaulting to 0) if the sequence is empty - the first and only element if the sequence only has one element - (...(((A + B) + C) + D) + ...) if the sequence has more than one element While this might be reasonable if the identity argument is not specified, I think that if an identity is specified, it should be used even if the sequence is non-empty. The reason being that the user might be relying on that to get the semantics he wants. Think of the second argument as accumulator object rather than identity. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
[Guido van Rossum] - the identity (defaulting to 0) if the sequence is empty - the first and only element if the sequence only has one element - (...(((A + B) + C) + D) + ...) if the sequence has more than one element [Greg Ewing] While this might be reasonable if the identity argument is not specified, I think that if an identity is specified, it should be used even if the sequence is non-empty. The reason being that the user might be relying on that to get the semantics he wants. Think of the second argument as accumulator object rather than identity. But I think the logical consequence of your approach would be that sum([]) should raise an exception rather than return 0, which would be backwards incompatible. Because if the identity element has a default value, the default value should be used exactly as if it were specified explicitly. Unfortunately my proposal is also backwards incompatible, since currently sum([1,1], 40) equals 42. I guess nobody remembers why we did it the way it is? -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Rationale for sum()'s design?
That is like Lisp's +, must be good :P Michael On Sun, 13 Mar 2005 08:38:42 -0800, Guido van Rossum [EMAIL PROTECTED] wrote: There are a few design choices we could have made for sum(); in particular, for non-empty sequences we could not have used the identity element (the optional second argument). As it is, we get unjustified but understandable complaints that sum() only supports numbers. An alternative design could have returned: - the identity (defaulting to 0) if the sequence is empty - the first and only element if the sequence only has one element - (...(((A + B) + C) + D) + ...) if the sequence has more than one element This has surprises too (in particular of returning 0 when invoked without overriding the identity argument for a seqence of addable non-numbers) but works without using the second argument for a larger set of inputs I believe it is often used in such a way that the input is known to be non-empty). I'd be happy to be pointed to a past discussion where this was considered and rejected with a good reason; then I can post that to the blog (where the deficiency in sum() is being berated a bit excessively). -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/michael.walter%40gmail.com ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com