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

Ethan Furman ethan at stoneleaf.us
Thu Apr 7 15:10:22 EDT 2016


On 04/07/2016 11:59 AM, Brett Cannon wrote:

> To make MAL's proposal concrete:
>
>    class StringLike(abc.ABC):
>
>      @abstractmethod
>      def __str__(self):
>          """Return the string representation of something."""
>
>    StringLike.register(pathlib.PurePath)  # Any 3rd-party library can do
> the same.
>
> 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 path.

I think I might like this better than a new magic method.

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

I don't understand.

--
~Ethan~



More information about the Python-ideas mailing list