[Python-Dev] Pathlib enhancements - acceptable inputs and outputs for __fspath__ and os.fspath()

Ethan Furman ethan at stoneleaf.us
Mon Apr 11 12:18:01 EDT 2016


On 04/10/2016 11:27 PM, Nick Coghlan wrote:
> On 11 April 2016 at 02:16, Ethan Furman <ethan at stoneleaf.us> wrote:

>>> DirEntry can still get the check, it can just throw TypeError when it
>>> represents a binary path (that's one of the advantages of using a
>>> method-based protocol - exceptions on method calls are more acceptable
>>> than exceptions on property access).
>>
>>
>> I guess I don't see the point of this.  Either DirEntry's [1] only get
>> partial support (which is only marginally better than the no support pathlib
>> currently has), or stdlib code will need to catch those errors and then do
>> an isinstance check to see if knows what the type is and how to deal with it
>> [1].
>
> What's wrong with only gaining partial support? Standard library code
> that doesn't currently support DirEntry at all will gain the ability
> to support str-based DirEntry objects, while bytes-based DirEntry
> objects will continue to be a low level object [...]

Let's consider to functions, one that accepts bytes/str for the path, 
and one that only accepts str:


   str-only support
   ----------------
   # before new protocol
   def do_fritz(a_path):
       if not isinstance(a_path, str):
           raise TypeError('str required')
       ...

   # after new protocol with str-only support
   def do_fritz(a_path):
       a_path = fspath(a_path)
       ...

   # after new protocol with bytes/str support
       a_path = fspath(a_path)
       if not isinstance(a_path, str):
           raise TypeError('str required')
       ...


   bytes/str support
   -----------------
   # before new protocol
   def zingar(a_path):
       if not isinstance(a_path, (bytes,str)):
           raise TypeError('bytes or str required')
       ...

   # after new protocol with str-only support
   def zingar(a_path):
       if not isinstance(a_path, bytes):
           try:
               a_path = fspath(a_path)
           except FSPathError:
               raise TypeError('bytes or str required')
       ...

   # after new protocol with bytes/str support
   def zingar(a_path):
       a_path = fspath(a_path)
       if not isinstance(a_path, (bytes,str)):
           raise TypeError('bytes or str required')
       ...


If those examples are anywhere close to accurate, an fspath protocol 
that supported both bytes and str seems a lot easier to work with.

--
~Ethan~


More information about the Python-Dev mailing list