<div dir="ltr"><br><br><div class="gmail_quote"><div dir="ltr">On Thu, 7 Apr 2016 at 11:43 M.-A. Lemburg <<a href="mailto:mal@egenix.com">mal@egenix.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On 07.04.2016 18:46, Chris Angelico wrote:<br>
> On Fri, Apr 8, 2016 at 2:27 AM, M.-A. Lemburg <<a href="mailto:mal@egenix.com" target="_blank">mal@egenix.com</a>> wrote:<br>
>> Not necessarily. In fact, a string.String ABC could have only<br>
>> a single method: .__str__() defined.<br>
><br>
> That wouldn't be very useful; object.__str__ exists and is functional,<br>
> so EVERY object would count as a string.<br>
<br>
No, only those objects that register with the ABC would be considered<br>
string-like, not all objects implementing the .__str__() method.<br>
In regular Python, only str() objects would register with<br>
strings.String.<br>
<br>
Path objects could also register to be treated as "string-like"<br>
object.<br>
<br>
Just like numeric types are only considered part of the ABCs<br>
under numbers, if they register with these.<br>
<br>
Perhaps the name strings.String sounds confusing, so<br>
perhaps strings.StringLike or strings.FineToConvertToAStringIfNeeded<br>
would be better :-)<br>
<br>
> The point of "string-like" is that it can be treated as a string, not<br>
> just that it can be converted to one. This is exactly parallel to the<br>
> difference between __index__ and __int__; floats can be converted to<br>
> int (and will truncate), but cannot be *treated* as ints.<br>
<br>
Right, and that's what you can define via an ABC. Those abstract<br>
base classes are not to be confused with introspecting methods<br>
on objects - they help optimize this kind of test, but most<br>
importantly help express the combination of providing an interface<br>
by exposing methods with the semantics of how those<br>
methods are expected to be used.<br></blockquote><div><br></div><div>To make MAL's proposal concrete:</div><div><br></div><div>  class StringLike(abc.ABC):</div><div><br></div><div>    @abstractmethod</div><div>    def __str__(self):</div><div>        """Return the string representation of something."""</div><div><br></div><div>  StringLike.register(pathlib.PurePath)  # Any 3rd-party library can do the same.</div><div><br></div><div>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.</div><div><br></div><div>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.</div></div></div>