[Python-ideas] The non-obvious nature of str.join (was Re: sum(...) limitation)

Nathaniel Smith njs at pobox.com
Mon Aug 11 23:53:12 CEST 2014


On 11 Aug 2014 22:36, "Ethan Furman" <ethan at stoneleaf.us> wrote:
>
> On 08/11/2014 02:25 PM, Nathaniel Smith wrote:
>>
>> On Mon, Aug 11, 2014 at 10:10 PM, Ethan Furman <ethan at stoneleaf.us>
wrote:
>>>
>>> On 08/11/2014 10:53 AM, Nathaniel Smith wrote:
>>>>
>>>>
>>>>
>>>> But practically speaking, how would this work? In general str.join and
>>>> sum have different semantics. What happens if we descend deep into the
>>>> iterable and then discover a non-string (that might nonetheless still
>>>> have a + operator)?
>>>
>>>
>>>
>>> The same thing that happens now if you pass a list to join with a
non-string
>>> entry:
>>>
>>> --> ' '.join(['some', 'list', 'of', 'words', 'and', 10, 'as', 'a',
>>> 'number'])
>>> Traceback (most recent call last):
>>>    File "<stdin>", line 1, in <module>
>>> TypeError: sequence item 5: expected string, int found
>>
>>
>> class Nasty:
>>      def __radd__(self, other):
>>          return other + "foo"
>>
>> "".join(["some", "strings", "and", "one", Nasty()])
>> sum(["some", "strings", "and", "one", Nasty()], "")
>
>
> Quite frankly, I regard this as a point in sum's favor.  We have,
effectively, a string-subclass and join chokes on it.

Yes, but the proposal I was responding to was to do something like

def sum(it, start=0):
    if start == "":
        return "".join(it)
    ... regular sum impl here ...

And the point is that this is not trivially a transparent optimization.

-n
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140811/e8e371c9/attachment-0001.html>


More information about the Python-ideas mailing list