Contextual operator overloading
For three weeks already I am struggling with this basic requirement: overload the arithmetic operators of Python without using class methods.
Or, more specifically, delegate the implementation of an infix operator to a third-party object in a specific context. For example, I would like something like the following code to work:
def foo(a, b):
print "hello ", a, "and", b
__builtins__.__add__ = foo
12 + 13 # use foo since __add__ is overloaded
Unfortunately, this does not work. Python optimizes arithmetic over basic types. And until now I can find no other “elegant” way to overload infix operators without specific object classes.
And no, this trick to overload infix operators is very ugly.
Publication Date: