sum and strings

Tim Chase python.list at tim.thechases.com
Wed Aug 23 17:24:25 EDT 2006


> Maybe he's just insisting on the principle of least surprise?
> Personally, I'd rather expect sum() to work for strings and Python to
> issue a warning instead of raising a type error. That warning might
> also be appropriate when using sum() on other builtin sequence types.

In its own way, it makes good sense to not be surprising:

 >>> # using regular number
 >>> n1 = 1
 >>> n2 = 2
 >>> sum([n1,n2])
3

 >>> # using complex numbers
 >>> c1 = 1+2j
 >>> c2 = 5+11j
 >>> sum([c1,c2])
(6+13j)

 >>> # using quaternion-ish objects
 >>> class Q(object):
...     def __init__(self, n, i,j,k):
...             self.n = n
...             self.i = i
...             self.j = j
...             self.k = k
...     def __add__(self, other):
...             return Q(self.n+other.n,
...                     self.i+other.i,
...                     self.j+other.j,
...                     self.k+other.k)
...
 >>> q1 = Q(1,2,3,5)
 >>> q2 = Q(7,11,13,17)
 >>> q3 = q1 + q2
 >>> q3.n, q3.i, q3.j, q3.k
(8, 13, 16, 22)
 >>> sum([q1,q2])
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'q'


Just because something is slow or sub-optimal doesn't mean it 
should be an error.  Otherwise calls to time.sleep() should throw 
an error...

 >>> time.sleep(1000)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
InefficentError: call takes more than 1 second to complete


[scratches head]

+1 regarding principle of least surprise on sum()

-tkc






More information about the Python-list mailing list