sum() requires number, not simply __add__
Peter Otten
__peter__ at web.de
Fri Feb 24 03:29:20 EST 2012
Buck Golemon wrote:
> I feel like the design of sum() is inconsistent with other language
> features of python. Often python doesn't require a specific type, only
> that the type implement certain methods.
>
> Given a class that implements __add__ why should sum() not be able to
> operate on that class?
>
> We can fix this in a backward-compatible way, I believe.
>
> Demonstration:
> I'd expect these two error messages to be identical, but they are
> not.
>
> >>> class C(object): pass
> >>> c = C()
> >>> sum((c,c))
> TypeError: unsupported operand type(s) for +: 'int' and 'C'
> >>> c + c
> TypeError: unsupported operand type(s) for +: 'C' and 'C'
You could explicitly provide a null object:
>>> class Null(object):
... def __add__(self, other):
... return other
...
>>> null = Null()
>>> class A(object):
... def __init__(self, v):
... self.v = v
... def __add__(self, other):
... return A("%s+%s" % (self, other))
... def __str__(self):
... return self.v
... def __repr__(self):
... return "A(%r)" % self. v
...
>>> sum(map(A, "abc"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'A'
>>> sum(map(A, "abc"), null)
A('a+b+c')
More information about the Python-list
mailing list