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

Terry Reedy tjreedy at udel.edu
Tue Aug 12 00:15:18 CEST 2014


On 8/11/2014 5:35 PM, Ethan Furman wrote:
> On 08/11/2014 02:25 PM, Nathaniel Smith wrote:

>> class Nasty:
>>      def __radd__(self, other):
>>          return other + "foo"
>>
>> "".join(["some", "strings", "and", "one", Nasty()])
>> sum(["some", "strings", "and", "one", Nasty()], "")

I don't understand the point of this.

> Quite frankly, I regard this as a point in sum's favor.  We have,
> effectively, a string-subclass and join chokes on it.

Nasty is a subclass of object, with no default value.  Make it a real 
str subclass and join works fine.

class Nasty(str):
     def __radd__(self, other):
         return other + "foo"

print("".join(["some", "strings", "and", "one", Nasty()]))
 >>>
somestringsandone



-- 
Terry Jan Reedy



More information about the Python-ideas mailing list