Why does str not have a __radd__ method?

Jason Swails jason.swails at gmail.com
Wed Aug 13 14:36:55 EDT 2014


On Wed, Aug 13, 2014 at 1:55 PM, Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:

> Ethan Furman wrote:
>
> > On 08/13/2014 09:00 AM, Steven D'Aprano wrote:
> >>
> >> What is the rationale for str not having __radd__ method?
> >
> > At a guess I would say because string only knows how to add itself to
> > other strings, so __add__ is sufficient.
>
> # Python 2.7
> py> "Hello" + u"World"
> u'HelloWorld'
> py> unicode.__radd__
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: type object 'unicode' has no attribute '__radd__'
>

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__.

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):

>>> 'this' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> u'this' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, int found


All the best,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140813/be4d06eb/attachment.html>


More information about the Python-list mailing list