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

Brett Cannon brett at python.org
Thu Apr 7 14:59:20 EDT 2016

On Thu, 7 Apr 2016 at 11:43 M.-A. Lemburg <mal at egenix.com> wrote:

> On 07.04.2016 18:46, Chris Angelico wrote:
> > On Fri, Apr 8, 2016 at 2:27 AM, M.-A. Lemburg <mal at egenix.com> wrote:
> >> Not necessarily. In fact, a string.String ABC could have only
> >> a single method: .__str__() defined.
> >
> > That wouldn't be very useful; object.__str__ exists and is functional,
> > so EVERY object would count as a string.
> No, only those objects that register with the ABC would be considered
> string-like, not all objects implementing the .__str__() method.
> In regular Python, only str() objects would register with
> strings.String.
> Path objects could also register to be treated as "string-like"
> object.
> Just like numeric types are only considered part of the ABCs
> under numbers, if they register with these.
> Perhaps the name strings.String sounds confusing, so
> perhaps strings.StringLike or strings.FineToConvertToAStringIfNeeded
> would be better :-)
> > The point of "string-like" is that it can be treated as a string, not
> > just that it can be converted to one. This is exactly parallel to the
> > difference between __index__ and __int__; floats can be converted to
> > int (and will truncate), but cannot be *treated* as ints.
> Right, and that's what you can define via an ABC. Those abstract
> base classes are not to be confused with introspecting methods
> on objects - they help optimize this kind of test, but most
> importantly help express the combination of providing an interface
> by exposing methods with the semantics of how those
> methods are expected to be used.

To make MAL's proposal concrete:

  class StringLike(abc.ABC):

    def __str__(self):
        """Return the string representation of something."""

  StringLike.register(pathlib.PurePath)  # Any 3rd-party library can do the

You could also call the class StringablePath or something and get the exact
same concept across where you are using the registration abilities of ABCs
to semantically delineate when a class's __str__() returns a usable file

The drawback is that this isn't easily backported like `path.__ospath__()
if hasattr(path, '__ospath__') else path` for libraries that don't
necessarily have access to pathlib but want to be compatible with accepting
path objects.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160407/a051c8e1/attachment.html>

More information about the Python-ideas mailing list