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

Chris Angelico rosuav at gmail.com
Thu Apr 7 11:37:49 EDT 2016

On Fri, Apr 8, 2016 at 1:26 AM, Paul Moore <p.f.moore at gmail.com> wrote:
> 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).

The original use-case was Path objects, which stringify as the
human-readable representation of the file system path. If you need to
pass a string-or-Path to something that requires a string, you need to
convert the Path to a string, but *not* convert other arbitrary
objects to strings; calling str(x) would happily convert the integer
1234 into the string "1234", and then you'd go trying to create that
file in the current directory. Python does not let you append
non-strings to strings unless you write __radd__ manually; this
proposal would allow objects to declare to the interpreter "hey, I'm
basically a string here", and allow Paths and strings to interoperate.


More information about the Python-ideas mailing list