[Python-Dev] pathlib - current status of discussions

Nick Coghlan ncoghlan at gmail.com
Wed Apr 13 23:27:41 EDT 2016

On 14 April 2016 at 13:14, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 04/13/2016 07:57 PM, Nikolaus Rath wrote:
>> Either I haven't understood your answer, or you haven't understood my
>> question. I'm concerned about this case:
>>    class Special(bytes):
>>        def __fspath__(self):
>>          return 'str-val'
>>    obj = Special('bytes-val', 'utf8')
>>    path_obj = fspath(obj, allow_bytes=True)
>> With #2, path_obj == 'bytes-val'. With #3, path_obj == 'str-val'.
> I misunderstood your question.  That is... an interesting case.  ;)

In this kind of case, inheritance tends to trump protocol. For
example, int subclasses can't override operator.index:

>>> from operator import index
>>> class NotAnInt():
...     def __index__(self):
...         return 42
>>> index(NotAnInt())
>>> class MyInt(int):
...     def __index__(self):
...         return 42
>>> index(MyInt(53))

The reasons for that behaviour are more pragmatic than philosophical:
builtins and their subclasses are extensively special-cased for speed
reasons, and those shortcuts are encountered before the interpreter
even considers using the general protocol.

In cases where the magic method return types are polymorphic (so
subclasses may want to override them) we'll use more restrictive exact
type checks for the shortcuts, but that argument doesn't apply for
typechecked protocols where the result is required to be an instance
of a particular builtin type (but subclasses are considered


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list