sum() requires number, not simply __add__

Buck Golemon buck at yelp.com
Thu Feb 23 22:23:45 CET 2012


On Feb 23, 1:19 pm, Buck Golemon <b... at yelp.com> 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'

Proposal:

def sum(values,
base=0):
      values =
iter(values)

      try:
          result = values.next()
      except StopIteration:
          return base

      for value in values:
          result += value
      return result



More information about the Python-list mailing list