[Python-ideas] Dunder method to make object str-like

Paul Moore p.f.moore at gmail.com
Thu Apr 7 11:26:26 EDT 2016

On 7 April 2016 at 16:05, Émanuel Barry <vgr255 at live.ca> wrote:
>> Hmmm -- so maybe you are saying that if the results of __str__ and
>> __tostring__ are the same we're fine, just like if the results of
>> __int__ and __index__ are the same we're fine?  Otherwise an error is
>> raised.
> Pretty much; as above, if __tostring__ (in absence of a better name) is
> defined and does not raise, it should return the same as __str__.

OK, that makes sense as a definition of "what __tostring__ does". But
I'm struggling to think of an example of code that would legitimately
want to *use* it (unlike __index__ where the obvious motivating case
was indexing a sequence). And even with a motivating example of use, I
don't know that I can think of an example of something other than a
string that might *provide* the method.

The problem with the "ASCII byte string" example is that if a type
provides __tostring__ I'd expect it to work for all values of that
type. I'm not clear if "ASCII byte string" is intended to mean "a
value of type bytes that only contains ASCII characters", or "a type
that subclasses bytes to refuse to allow non-ASCII". The former would
imply __tostring__ working sometimes, but not always. The latter seems
like a contrived example (although I'm open to someone explaining a
real-world use case where it's important).


More information about the Python-ideas mailing list