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

Ethan Furman ethan at stoneleaf.us
Thu Apr 7 11:43:31 EDT 2016


On 04/07/2016 08:37 AM, Chris Angelico wrote:
> On Fri, Apr 8, 2016 at 1:26 AM, Paul Moore wrote:

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

The problem with that is that Paths are conceptually not strings, they 
just serialize to strings, and we have a lot of infrastructure in place 
to deal with that serialized form.

Is there anything, anywhere in the Python ecosystem, that would also 
benefit from something like an __as_str__ method/attribute?

--
~Ethan~



More information about the Python-ideas mailing list