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

Chris Angelico rosuav at gmail.com
Thu Apr 7 11:42:07 EDT 2016


On Fri, Apr 8, 2016 at 1:26 AM, M.-A. Lemburg <mal at egenix.com> wrote:
> On 07.04.2016 16:58, MRAB wrote:
>> On 2016-04-07 15:10, M.-A. Lemburg wrote:
>>> On 07.04.2016 15:04, Chris Angelico wrote:
>>>> This is a spin-off from the __fspath__ discussion on python-dev, in
>>>> which a few people said that a more general approach would be better.
>>>>
>>>> Proposal: Objects should be allowed to declare that they are
>>>> "string-like" by creating a dunder method (analogously to __index__
>>>> for integers) which implies a loss-less conversion to str.
>>>
>>> I must be missing something... we already have a method for this:
>>> .__str__()
>>>
>> It's for making string-like objects into strings.
>>
>> __str__ isn't suitable because, ints, for example, have a __str__
>> method, but they aren't string-like.
>
> Depends on what you define as "string-like", I guess :-)
>
> We have abstract base classes for such tests, but there's nothing
> which would define "string-like" as ABC. Before trying to define
> a test via a special method, I think it's better to define what
> exactly you mean by "string-like".
>
> Something along the lines of numbers.Number, but for strings.
>
> To make an object string-like, you then test for the ABC and
> then call .__str__() to get the string representation as string.

The trouble with the ABC is that it implies a large number of methods;
to declare that your object is string-like, you have to define a
boatload of interactions with other types, and then decide whether
str+Path yields a Path or a string. By defining __tostring__ (or
whatever it gets called), you effectively say "hey, go ahead and cast
me to str any time you need a str". Instead of defining all those
methods, you simply define one thing, and then you can basically just
treat it as a string thereafter.

While you could do this by simply creating a whole lot of methods and
making them all return strings, you'd still have the fundamental
problem that you can't be sure that this is "safe". How do you
distinguish between "object that can be treated as a string" and
"object that knows how to add itself to a string"? Hence, this.

ChrisA


More information about the Python-ideas mailing list