Automatically generating arithmetic operations for a subclass

Arnaud Delobelle arnodel at googlemail.com
Tue Apr 14 06:16:04 EDT 2009


Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:

> I have a subclass of int where I want all the standard arithmetic 
> operators to return my subclass, but with no other differences:
>
> class MyInt(int):
>     def __add__(self, other):
>         return self.__class__(super(MyInt, self).__add__(other))
>     # and so on for __mul__, __sub__, etc.
>
>
> My quick-and-dirty count of the __magic__ methods that need to be over-
> ridden comes to about 30. That's a fair chunk of unexciting boilerplate.
>
> Is there a trick or Pythonic idiom to make arithmetic operations on a 
> class return the same type, without having to manually specify each 
> method? I'm using Python 2.5, so anything related to ABCs are not an 
> option.
>
> Does anyone have any suggestions?

I do this:

binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc
unops = ['neg', 'abs', invert'] # etc
 
binop_meth = """
def __%s__(self, other):
    return type(self)(int.__%s__(self, other))
"""

unop_meth = """
def __%s__(self):
    return type(self)(int.__%s__(self))
"""

class MyInt(int):
      for op in binops:
          exec binop_meth % (op, op)
      for op in unops:
          exec unop_meth % (op, op)
      del op

HTH

-- 
Arnaud



More information about the Python-list mailing list