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

Joshua Landau joshua at landau.ws
Tue Jul 23 11:21:11 CEST 2013


On 23 July 2013 08:24, Andrew Barnert <abarnert at yahoo.com> wrote:

> On Jul 19, 2013, at 4:16, Sergey <sergemp at mail.ru> wrote:
> > Nope, still wrong. Just in case she tries to remove a star, that she
> > don't understand anyway:
> >>> for i in list(chain(list_of_sets)):
> >>>     deal_with(i)
> > Still no go. So after all these attempts she asks someone smart and
> > finally gets the correct code:
> >>> for i in aset(chain(list_of_sets)):
> >>>     deal_with(i)
>

That doesn't work because you want chain.from_iterable instead of chain. Or
the star you're so fond of. I really think, in retrospect, that
chain.from_iterable should be chain (you can always use chain([things]) to
get the old behaviour). It's the behaviour people normally want, and it
seems people often accidentally fall back to plain chain too easily.

Plus, loads of people don't know of chain.from_iterable, for some strange
reason.


>  This isn't really a good solution. It may work, but if you want to union
> a bunch of sets, you shouldn't try to spell it as chaining iterables into a
> set constructor.


Why? It makes sense to me, and it's not less-efficient than the loop
(except that it's not a C-loop, but that's not normally important) and I
think it's more readable simply because it's shorter, so you can move on to
the actual point of whatever you're doing.



> > * something(chain(*list_of_something))
> > may be correct or may be not
>
> This is not something you should generally want to do.
>
> Remember that the whole point of the iteration protocols is that you
> generally don't care what type you're iterating over. And when you do care,
> you usually want to build a collection of some specific type out of an
> iterable, again without caring about the original type. You want a list, or
> a blist.sortedlist, or whatever, and it doesn't matter that what was passed
> in was a list, a tuple, or something else.


+1

Note that in the sortedlist situation, I believe there are merge sorts you
should be doing, but they aren't generalisable.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130723/ee0a3fd5/attachment.html>


More information about the Python-ideas mailing list