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