[Python-ideas] Dunder method to make object str-like
brett at python.org
Thu Apr 7 15:10:00 EDT 2016
On Thu, 7 Apr 2016 at 12:03 Chris Barker <chris.barker at noaa.gov> wrote:
> On Thu, Apr 7, 2016 at 11:59 AM, Brett Cannon <brett at python.org> wrote:
>> class StringLike(abc.ABC):
>> 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.
>> 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.
> and a plus is that it's compatible with type hinting -- is that the future
> of Python???
So the other way to do this is to combine the proposals:
"""Return the file system path, serialized as a string."""
Then pathlib.PurePath can inherit from this ABC and anyone else can as well
or be registered as doing so. Then in typing.py you can have:
__slots__ = ()
PathLike = Union[str, Path]
Then any third-party library can register with the ABC and get the typing
correctly (assuming I didn't botch the type specification).
Guido also had some protocol proposal a while back that I think he floated
here, but I don't think the discussion really went anywhere as it was an
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas