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

Ethan Furman ethan at stoneleaf.us
Mon Aug 11 23:35:50 CEST 2014


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.

--
~Ethan~


More information about the Python-ideas mailing list