Automatically generating arithmetic operations for a subclass

norseman norseman at
Wed Apr 15 02:28:42 CEST 2009

Steven D'Aprano wrote:
> 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?
Have you thought about making a generator?
The boiler plate is above. Change the necessary parts to VARS and place 
in a loop to write them out. Input file would have the 30 +/- lines to 
be substituted.
zparts contents:
MyInt, __add__, other
MyMul, __mul__, other
zgen contents:
while read ztyp,zop,zother
    print (line one..
    print (line two..
    print "return self.__class__(super($ztyp, self).&zop(zother))

(syntax not necessarily correct, but you get the idea)
Run redirected to lib or program source.


More information about the Python-list mailing list