Home > Enterprise >  Python namedtuples elementwise addition
Python namedtuples elementwise addition

Time:07-08

Is there a more pythonic way to implement elementwise addition for named tuples?

Using this class that inherits from a namedtuple generated class named "Point I can do elementwise addition for this specific named tuple.

    class Point(namedtuple("Point", "x y")):
    def __add__(self, other):
        return Point(x = self.x   other.x, y = self.y   other.y)

If we use this functionality:

print(Point(x = 1, y = 2)   Point(x = 3, y = 1))

The result is:

Point(x=4, y=3)

Is there a more pythonic way to do this in general? Is there a generalized way to do this that can extend elementwise addition to all namedtuple generated objects?

CodePudding user response:

(Named)tuples are iterable, so you could use map and operator.add. Whether this is an improvement is debatable. For 2D points, almost certainly not, but for higher-dimensional points, it would be.

from operator import add


class Point(namedtuple("Point", "x y")):

    def __add__(self, other):
        return Point(*map(add, self, other))

CodePudding user response:

This is a possible solution:

class Point(namedtuple("Point", "x y")):
    def __add__(self, other):
        return Point(**{field: getattr(self, field)   getattr(other, field)
                        for field in self._fields})
  • Related