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

Nick Coghlan ncoghlan at gmail.com
Mon Apr 18 03:41:16 EDT 2016


On 18 April 2016 at 07:05, Koos Zevenhoven <k7hoven at gmail.com> wrote:

> On Sun, Apr 17, 2016 at 9:14 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> > On 04/17/2016 06:58 AM, Koos Zevenhoven wrote:
> >
> >> So, as a summary: With a str+bytes-polymorphic __fspath__, with the
> >> above argumentation and the rough implementation of os.fspath(...),
> >> the conclusion is that the os.fspath function should indeed be public,
> >> and that no further variations are needed.
> >
> >
> > Nice summation, thank you.  :)
> >
>
> Come on, Ethan, that summary was not for you ;)


As Chris noted though, the "Yes, that summary is accurate" from active
participants in the discussion helps assure readers that it's a good
overview :)

Given the variant you suggested, what if we defined the API semantics like
this:

    # Offer the simplest possible API as the public vesion
    def fspath(pathlike) -> str:
        return os._raw_fspath(pathlike)

    # Expose the complexity in the "private" variant
    def _raw_fspath(pathlike, *, output_types = (str,)) -> (str, bytes):
        # Short-circuit for instances of the output type
        if isinstance(pathlike, output_types):
            return pathlike
        # We'd have a tidier error message here for non-path objects
        result = pathlike.__fspath__()
        if not isinstance(result, output_types):
            raise TypeError("argument is not and does not provide an
acceptable pathname")
        return result

That way, the default API would be saying unambiguously that the preferred
way of manipulating filesystem paths is as text, but the lower level
"mainly for the standard library" API would explicitly handle the 3
different scenarios (binary-input-is-a-bug, text-input-is-a-bug, and
either-binary-or-text-input-is-fine).

That way the structure of the additional parameters on _raw_fspath can be
tailored specifically to the needs of the standard library, without
worrying as much about 3rd party use cases.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20160418/dd5bf3a4/attachment.html>


More information about the Python-Dev mailing list