[Python-ideas] Another attempt at a sum() alternative: the concatenation protocol

David Mertz mertz at gnosis.cx
Wed Jul 17 17:23:47 CEST 2013


> Imagine a type, that somehow modifies items that it stores, removes
> duplicates, or sorts them, or something else, e.g.:
>   class aset(set):
>       def __add__(self, other):
>           return self|other
>
> Now we have a code:
>   list_of_sets = [ aset(["item1","item2","item3"]) ] * 1000
>   [...]
>   for i in sum(list_of_sets, aset()):
>       deal_with(i)
>
> If you replace `sum` with `chain` you get something like:
>   for i in chain.from_iterable(list_of_sets):
>       deal_with(i)
>
> Which works! (that's the worst part) but produces WRONG result!

In this example you can use:

aset(chain(list_of_sets))

This gives the same answer with the same big-O runtime.  It's possible to
come up with more perverse customizations where this won't hold. But I
think all of them involve redefining __add__ as something with little
relation to it's normal meaning. Odd behavior in those cases is to be
expected.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130717/3b8f12da/attachment.html>


More information about the Python-ideas mailing list