Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for + when using sum

I have a class with my own implementation of __add__:

class Point(namedtuple('Point', ['x', 'y', 'z'])):
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y, self.z + other.z)

Addition works as expected:

l = [Point(0,0,0), Point(0,1,2)]
s = l[0]
for a in l[1:]:
    s = s + a

But when I use builtin sum I'm getting an error:

s = sum(l)

TypeError: unsupported operand type(s) for +: 'int' and 'Point'

What's wrong in my code? Doesn't sum use __add__? What more should I override?

like image 556
sygi Avatar asked Mar 18 '26 20:03

sygi


2 Answers

The sum function initializes its result variable with the integer value 0:

sum(iterable[, start]) -> value

    Return the sum of an iterable of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).

So inside of sum, the addition 0 + Point(0,0,0) is performed, which your class doesn't support.

To get around this, pass a suitable value for start:

s = sum(l, Point(0,0,0))
like image 131
Aran-Fey Avatar answered Mar 21 '26 08:03

Aran-Fey


You could also override the __radd__() function:

def __radd__(self, other):
    return Point(self.x + other, self.y + other, self.z + other)

Note that this must be done additionally to overriding __add__()

like image 41
rammelmueller Avatar answered Mar 21 '26 08:03

rammelmueller