[Python-ideas] Working with Path objects: p-strings?

Koos Zevenhoven k7hoven at gmail.com
Wed Mar 30 14:24:05 EDT 2016


On Wed, Mar 30, 2016 at 6:18 PM, Paul Moore <p.f.moore at gmail.com> wrote:
>
> Of course this doesn't address functions that *return* paths (as
> strings). There the caller has to wrap the return value in Path(). Or
> the function changes to return Path objects, which won't be backward
> compatible (whether that matters depends on what the code is).
>

So, below was a though of how to deal with this: StringPath, which is
both a str and a Path (and/or perhaps PurePath).

On Sun, Mar 27, 2016 at 2:33 AM, Koos Zevenhoven <k7hoven at gmail.com> wrote:
>
> Well, just to reply to myself, here's a slightly crazy idea, which I'll
> mention before I realize that it's a bad idea:
>
> What if there was a another class, say StringPath, that inherits from both
> str and Path, which wraps another instance of Path, but is also a str. When
> you call its Path methods, it would delegate them to the wrapped Path object
> so that functions that now return paths as plain str could in future
> versions start returning that type?

While I still think it's a crazy idea, I'm not 100% convinced that it
is the wrong thing to do, because there are already many kinds of Path
objects. So a wrote a super hacky implementation of StringPath.
Instances of something like this could be returned from functions that
now return paths in strings.

Here's a little demo with the toy implementation:

    >>> p = StringPath("foo/bar/baz")
    >>> p
    StringPath(PosixPath('foo/bar/baz'))
    >>> isinstance(p, pathlib.Path)
    True
    >>> isinstance(p, str)
    True
    >>> str(p)
    'foo/bar/baz'
    >>> p + 'hello'
    'foo/bar/bazhello'
    >>> p / 'hello'
    PosixPath('foo/bar/baz/hello')
    >>> 'hello' / p
    PosixPath('hello/foo/bar/baz')
    >>> p.split('r')
    ['foo/ba', '/baz']
    >>> pathlib.Path(p)
    PosixPath('foo/bar/baz')

So it's a str, but as soon as you do something Path-like with it, it
gives you a Path back. But for anyone who thinks they have a string,
it's a string, except for its repr.

-Koos

P.S. The implementation I used here is actually completely ridiculous,
but if you want to look at it, it's here:

https://gist.github.com/k7hoven/defb7f2eb9ccd9dbd0be0063a475058e


More information about the Python-ideas mailing list