[Python-Dev] Pathlib enhancements - acceptable inputs and outputs for __fspath__ and os.fspath()
Paul Moore
p.f.moore at gmail.com
Sat Apr 16 08:05:25 EDT 2016
On 16 April 2016 at 12:21, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> OK, you win, __fspath__ needs to be polymorphic.
>
> But you've just shifted me to -1 on "os.fspath": it's an attractive
> nuisance. EIBTI, applications and high-level library functions should
> use os.fsdecode or os.fsencode.
I presume your expectation is that os.fsencode/os.fsdecode will work
with objects supporting the __fspath__ protocol?
So the question for me is, if I'm writing a function that takes a path
argument p (in the most general sense - I want my function to be able
to handle anything the stdlib functions can) then how do I write the
code? There are 4 cases I can think of:
1. I just want to pass the argument on to other functions - just do
so, stdlib functions will work fine.
2. I need a string - use os.fsdecode(p)
3. I need bytes - use os.fsencode(p)
4. I need a guaranteed pathlib.Path object so that I can use Path
methods - convert via pathlib.Path(os.fsdecode(p))
I guess there's the possibility that you want to deliberately reject
bytes-like paths, and it's not immediately obvious how you'd do that
without os.fspath or using the __fspath__ protocol directly, but I'm
not sure what anyone gains by doing so (maybe the chance to fail
early? but doesn't using fsdecode mean I never need to fail at all?)
While I don't have any specific reason to object to os.fspath, I'd
appreciate someone describing a concrete use case that needs it (and
isn't covered by any of the options above).
Paul
More information about the Python-Dev
mailing list