sum
is effectively implemented like this:
def sum(sequence, start=0):
for value in sequence:
start = start + value
return start
So, you can't override sum
directly… but if you can override the way for value in …
works on your sequence,* or the way +
works on your values, that will affect sum
automatically. Of course either one will have side effects—you'll be affecting any iteration of your sequence, or any addition of your values, not just the ones inside sum
.
To override iteration, you need to provide a __iter__
method that returns an appropriate iterator. To override addition, you need to provide a __add__
method.
But really, why are you trying to "override sum"? Why not just write a new function that does what you want? You can add code that special-cases your type(s) and then falls back to the builtin sum
otherwise. If you want to make it more "open", you can use PEP 443 single-dispatch to make it easy to register new types to be special-cased. I think that's what you really want here.
* As agf points out in the comments, despite the parameter being called sequence
, it actually takes any iterable. Which is a good thing, because dictionaries aren't sequences…