<div dir="ltr"><div class="gmail_default" style="color:rgb(0,0,0)"><br></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Wed, Aug 13, 2014 at 1:55 PM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve+comp.lang.python@pearwood.info" target="_blank">steve+comp.lang.python@pearwood.info</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex"><div class="">Ethan Furman wrote:<br>
<br>
> On 08/13/2014 09:00 AM, Steven D'Aprano wrote:<br>
>><br>
</div><div class="">>> What is the rationale for str not having __radd__ method?<br>
><br>
</div><div class="">> At a guess I would say because string only knows how to add itself to<br>
> other strings, so __add__ is sufficient.<br>
<br>
</div># Python 2.7<br>
py> "Hello" + u"World"<br>
u'HelloWorld'<br>
py> unicode.__radd__<br>
<div class="">Traceback (most recent call last):<br>
  File "<stdin>", line 1, in <module><br>
</div>AttributeError: type object 'unicode' has no attribute '__radd__'<br></blockquote><div><br></div><div class="gmail_default" style="color:rgb(0,0,0)">This happens because the str.__add__ function calls string_concat under the hood (see Objects/stringobject.c) -- there's a unicode check on the other operand that results in the result of PyUnicode_Concat being returned instead of the concatenated str type.  This doesn't require that unicode define __radd__.</div>
<div class="gmail_default" style="color:rgb(0,0,0)"><br></div><div class="gmail_default" style="color:rgb(0,0,0)">When the left-hand operand is Unicode, PyUnicode_Concat is called directly (which is why the exception message is different for u'this' + 1 and 'this' + 1):</div>
<div class="gmail_default" style="color:rgb(0,0,0)"><br></div><div class="gmail_default" style="color:rgb(0,0,0)"><div class="gmail_default">>>> 'this' + 1</div><div class="gmail_default">Traceback (most recent call last):</div>
<div class="gmail_default">  File "<stdin>", line 1, in <module></div><div class="gmail_default">TypeError: cannot concatenate 'str' and 'int' objects</div><div class="gmail_default">
>>> u'this' + 1</div><div class="gmail_default">Traceback (most recent call last):</div><div class="gmail_default">  File "<stdin>", line 1, in <module></div><div class="gmail_default">
TypeError: coercing to Unicode: need string or buffer, int found</div><div><br></div><div><br></div><div>All the best,</div><div>Jason</div></div></div>
</div></div>