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

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jul 16 16:14:10 CEST 2013


On 16 July 2013 13:59, Ron Adam <ron3200 at gmail.com> wrote:
> On 07/16/2013 06:06 AM, Oscar Benjamin wrote:
>> On 16 July 2013 11:37, Ronald Oussoren <ronaldoussoren at mac.com> wrote:
>>> On 16 Jul, 2013, at 12:21, Oscar Benjamin <oscar.j.benjamin at gmail.com>
>>> wrote:
>>>> On 16 July 2013 07:50, Nick Coghlan <ncoghlan at gmail.com> wrote:
>>>>>
>>>>>     def concat(start, iterable, *, interleave=None):
>>>>>         try:
>>>>>             build = start.__concat__
>>>>>         except AttributeError:
>>>>>             result = start
>>>>>             if interleave is None:
>>>>>                 for x in iterable:
>>>>>                     result += x
>>>>>             else:
>>>>>                 for x in iterable:
>>>>>                     result += interleave
>>>>>                     result += x
>>>>>         else:
>>>>>             result = build(iterable, interleave=interleave)
>>>>
>>>> That doesn't seem like a very nice signature e.g.:
>>>> It's worse with an iterator:
>>>>
>>>>     it = iter(iterable)
>>>>     try:
>>>>         start = next(it)
>>>>     except StopIteration:
>>>>         result = ''
>>>>     else:
>>>>         result = concat(start, it, interleave=sep)
>>>>
>>>> Or have I misunderstood?
>>>
>>> concat('', iterable, interleave=sep) should work.
>>
>> Not with the code as shown. The result would be prepended with sep.
>
> It would be a TypeError.
>
> The part you are misunderstanding is this all depends on weather or not a
> builtin version of this can be significantly faster than chain.  And/or if
> there is enough use cases where this will be beneficial.

No, looking at it I think that the part I misunderstood was that Nick
intended for the concat function to behave in a slightly different way
than the example code which places the interleave value between start
and iterable[0].

> Ideas like this don't just get in automatically, they still need to be
> "worth it".

True. I personally don't think that there is any problem with summing
lists not because I think that it's a good thing to do but because
it's already easy to fix any code that does that. If it is the case
that moving chain to builtins would help people to understand better
ways of writing code then that might be a good thing to do. For me it
would give the slight convenience that something I often use would be
available without an import (and with a better name). I really like
Joshua's PEP but I will probably still prefer chain to an unpacking
generator in most situations.


Oscar


More information about the Python-ideas mailing list