Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #76225
| References | <53eb8b8a$0$6574$c3e8da3$5496439d@news.astraweb.com> <mailman.12932.1407950830.18130.python-list@python.org> <53eba6a3$0$6574$c3e8da3$5496439d@news.astraweb.com> |
|---|---|
| Date | 2014-08-13 14:36 -0400 |
| Subject | Re: Why does str not have a __radd__ method? |
| From | Jason Swails <jason.swails@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.12936.1407955459.18130.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On Wed, Aug 13, 2014 at 1:55 PM, Steven D'Aprano < steve+comp.lang.python@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Why does str not have a __radd__ method? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-08-14 02:00 +1000
Re: Why does str not have a __radd__ method? Ethan Furman <ethan@stoneleaf.us> - 2014-08-13 10:27 -0700
Re: Why does str not have a __radd__ method? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-08-14 03:55 +1000
Re: Why does str not have a __radd__ method? Ethan Furman <ethan@stoneleaf.us> - 2014-08-13 11:22 -0700
Re: Why does str not have a __radd__ method? Jason Swails <jason.swails@gmail.com> - 2014-08-13 14:36 -0400
Re: Why does str not have a __radd__ method? wxjmfauth@gmail.com - 2014-08-13 23:24 -0700
csiph-web