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

Chris Angelico rosuav at gmail.com
Thu Apr 7 15:06:31 EDT 2016

On Fri, Apr 8, 2016 at 4:45 AM, Chris Barker <chris.barker at noaa.gov> wrote:
> On Thu, Apr 7, 2016 at 11:28 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> And this should make it easier for third-party code to be functional
>> without even being aware of the Path object. There are two basic
>> things that code will be doing with paths: passing them unchanged to
>> standard library functions (eg open()), and combining them with
>> strings. The first will work by definition; the second will if paths
>> can implicitly upcast to strings.
> so this is really a way to make the whole path!=string thing easier -- we
> don't want to simply call str() on anything that might be a path, because
> that will work on anything, whether it's the least bit pathlike at all, but
> this would introduce a new kind of __str__, so that only things for which it
> makes sense would "Just work":
> str + something
> Would only concatenate to a new string if somethign was an object that
> couuld "losslessly" be considered a string?
> but if we use the __index__ example, that is specifically "an integer that
> can be ued as an index", not "something that can be losslessly converted to
> an integer".

That's two ways of describing the same thing. When you call __index__,
you either get back an integer with the exact same meaning as the
original object, or you get an exception. In contrast, calling __int__
may result in an integer which is similar, but not equal, to the
original - for instance, int(3.2) is 3. That's a lossy conversion,
which __index__ will refuse to do.

Similarly, str() can be quite lossy and non-strict on arbitrary
objects. With this conversion, it will always either return an
exactly-equivalent string, or raise.

> so why not the __fspath__ protocol anyway?
> Unless there are all sorts of other use cases you have in mind?

Not actually in mind, but there have been multiple people raising
concerns that __fspath__ is too specific for what it achieves.


More information about the Python-ideas mailing list