6

I'd like to be able to write something like this in python:

a = (1, 2)
b = (3, 4)
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)

I realize that you can overload operators to work with custom classes, but is there a way to overload operators to work with pairs?

Of course, such solutions as

c = tuple([x+y for x, y in zip(a, b)])

do work, but, let aside performance, they aren't quite as pretty as overloading the + operator.

One can of course define add and mul functions such as

def add((x1, y1), (x2, y2)):
    return (x1 + x2, y1 + y2)

def mul(a, (x, y)):
    return (a * x, a * y)

but still being able to write q * b + r instead of add(times(q, b), r) would be nicer.

Ideas?

EDIT: On a side note, I realize that since + currently maps to tuple concatenation, it might be unwise to redefine it, even if it's possible. The question still holds for - for example =)

2
  • 2
    On a side note, a generator expression (tuple(x + y for x, y in zip(a,b))) saves the creation of the unneeded list.
    – user395760
    Apr 27, 2011 at 9:40
  • True; not exactly pretty yet, though :)
    – Clément
    Apr 27, 2011 at 9:42

7 Answers 7

7

In contrast to Ruby, you can't change the behaviour of built-in types in Python. All you can do is create a new type derived from a built-in type. Literals will still create the built-in type, though.

Probably the best you can get is

class T(tuple):
    def __add__(self, other):
        return T(x + y for x, y in zip(self, other))
    def __rmul__(self, other):
        return T(other * x for x in self)
a = T((1, 2))
b = T((3, 4))
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)
2
  • s/porbably/probably ;) Thanks!
    – Clément
    Apr 27, 2011 at 9:43
  • Side note: using complex numbers works too; don't know how it's implemented under the hood, and whether it would save performance.
    – Clément
    Apr 27, 2011 at 9:48
3

You can inherit a class from tuple and overload its __add__ method. Here's a very simplistic example:

class mytuple(tuple):
    def __add__(self, other):
        assert len(self) == len(other)
        return tuple([x + y for x, y in zip(self, other)])

mt = mytuple((5, 6))
print mt + (2, 3)  # prints (7, 9)

I wouldn't recommend this approach though, because tuples weren't really designed for this purpose. If you want to perform numeric computations, just use numpy.

2

You cannot modify types defined in C, so you would need to create all new types for this. Or you could just use NumPy, which already has types that support this.

2

There is the famous infix operator hack that would allow you to do soemthing like this:

x = Infix(lambda a,b:tuple([x+y for x, y in zip(a, b)]))
y = Infix(lambda a,b:tuple([a*y for y in b]))

c = a |x| b # c would be (4, 6)
d = 3 |y| b # d would be (9, 12) 

That would hide the generator expressions and be applicable to tuples of all lengths, at the expense of "weird" pseudo-operators |x| and |y|.

2

Using python complex numbers is definitely one way to do it, if not extremely pretty.

a = 1 + 2j
b = 3 + 4j
c = a + b # c would be 4 + 6j
d = 3 * b # d would be 9 + 12j

That saves the definition of an extra class.

Also, expanding on previous answers,

class T(tuple):
    def __add__((x, y), (x1, y1)):
        return T((x+x1, y+y1))
    def __rmul__((x, y), other):
        return T((other * x, other * y))

would improve performance, at the cost of restraining the implementation to pairs.

1
  • This may not be extremely pretty, but there's no reason for it to be ugly, either. The only real problem is cosmetic: pairs are presented as 1 + 2j instead of something like Pair(1,2). But subclassing complex requires only the str and repr methods to overridden to get something more appealing. Apr 27, 2011 at 9:58
1

Write your own class and implement __mul__, __add__ etc.

1

You can use numpy.array to get all you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.