Is there a mechanism that enables to define the null elements for operators (0 for addition, 1 for multiplication, etc)

Viewed 115

This is really a general question in Python, that rose with the following code:

class Toto():
    def __init__(self, val, n=""):
        self.val = val
        self.n = n
    def __repr__(self): return f"Toto({self.val}, {self.n})"
    def __add__(self, other):
        # Toto-casting
        if not isinstance(other, Toto):
            other = Toto(other, n="")
        return Toto(self.val+other.val, self.n+other.n)
    __radd__ = __add__

t = Toto(1, "1")
v = Toto(2, "11")
print(t+v)
print(sum([t, v]))

which prints as expected :

Toto(3, 111)
Toto(3, 111)

Now, for some reasons, I would like to remove the 2 Toto-casting lines in __add__, to ensure to raise an AttributeError when trying to add 2 objects that are not Toto instances - BUT I would also like that sum([t, v]) works. For this, the only workaround is to explicitely specify the initial value as

sum([t, v], Toto(0, "")) # outputs Toto(3, 111) as expected

Now what I was wondering is could it be possible to specify in the class the "null element for addition" in my class, that would be called by default as the initial value for sum ? Or in code, would this be acceptable (in a far-away python version for eg):

class Toto():
    # this attribute would be called by sum as 
    # "sum([t, v])" become "sum([t, v], t.__null_addition__)"
    __null_addition__ = Toto(0)
    
    def __init__(self, val, n=""):
        self.val = val
        self.n = n
    def __repr__(self): return f"Toto({self.val}, {self.n})"
    def __add__(self, other):
        #if not isinstance(other, Toto):
        #    other = Toto(other, n="")
        return Toto(self.val+other.val, self.n+other.n)
    __radd__ = __add__

I guess my question in the end is : why this implementation for sum would not be acceptable in python ? Why can't we define an "null element", also called "identity element" for operators in python classe ?

More generaly, this could be expanded to other operators like mul: in python, why is there no notion of "identity element" for operators (as defined in mathematical groups). This notion could be used to overload the default initial value of sumfor example (and maybe/probably more applications).

Hope its clear.

0 Answers
Related