[Python-ideas] Implement __add__ for set and frozenset

Brandon Mintern bmintern at gmail.com
Wed Jun 4 05:36:15 CEST 2008


On Tue, Jun 3, 2008 at 9:57 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Brandon Mintern wrote:
>>
>> Perhaps a better proposal would be "change max to use __iadd__ if
>> available, falling back to __add__ if not"

Obviously, I meant to say "sum" there instead of "max" (which I'm
pretty sure you realized as well) -- I had been using max at the time
that I wrote that e-mail.

> That could change the behaviour of existing code that
> passes a mutable initial value.
>
> --
> Greg

That was my intention, to take advantage of increased efficiency
provided by mutable initial values. Unfortunately, I didn't consider
the "existing code" problem, but that's not really a problem in Python
3K, is it?

For example, sum(lists, []) currently runs in quadratic time (as
pointed out by George Sakkis earlier in this thread using an example
of sets that implement __add__). If instead, sum was implemented as:

def sum (iterable, init=0):
   for i in iterable:
       init += i
   return init

Then its behavior would mimic its current behavior for immutable types
and other types which do not implement iadd, but for types that allow
more efficient value modification, it would be a big win.

Is there a good use case for a time when you wouldn't want an initial
value to be mutated? In my experience, I've always passed in throwaway
initial values anyways, like [].

Brandon

p.s. Sorry, Greg, for the dupe. Why don't the Python mailing lists
generate Reply-To headers? It's pretty annoying to always have to
remember to say "Reply to all" instead of simply "Reply".



More information about the Python-ideas mailing list