Automatically generating arithmetic operations for a subclass

Paul McGuire ptmcg at austin.rr.com
Tue Apr 14 05:55:43 EDT 2009


On Apr 14, 4:09 am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> 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.
>

Something like this maybe?

def takesOneArg(fn):
    try:
        fn(1)
    except TypeError:
        return False
    else:
        return True

class MyInt(int): pass

template = "MyInt.__%s__ = lambda self, other: self.__class__(super
(MyInt, self).__%s__(other))"
fns = [fn for fn in dir(int) if fn.startswith('__') and takesOneArg
(getattr(1,fn))]
print fns
for fn in fns:
    exec(template % (fn,fn))


Little harm in this usage of exec, since it is your own code that you
are running.

-- Paul



More information about the Python-list mailing list