For a user defined python type, have `a+b+c+d` do `summation(a,b,c,d)` instead of `((a+b)+c)+d`

Viewed 32

I have a type Foo for which calling summation(a,b,c,d) is much more efficient than performing additions a+b+c+d. Yet, it's way nicer to just write a+b+c+d.

A solution, as far as I understand, is to write a wrapper type DelayedSum so that Foo.__add__(a, b) will return DelayedSum([a, b]) and DelayedSum.__add__ does something similar. Then I need to provide for the calculation to be performed each time the object of type DelayedSum is used. It means that I need to define all the "magic" operators

class DelayedSum:
    ...
    def __len__(self):
        foo = summation(*self.foo_list) # this will be repeated everywhere, write decorator?
        return len(foo)  
    def __getattr__(self, value):
        ...

Also, I'm pretty sure this will start to get a bit awkward if someone starts using y = a+b+c and check y is of a given type or tries y.bar = 2. And I'm pretty much sure I forget a few issues.

Is there a standard way to proceed and/or a package for it? I'm certainly not the first one to need that but I have trouble to find the relevant info.

0 Answers
Related