Python 3.4+: Extending pathlib.Path

2.6k views Asked by At

The following code is what I tried first, but some_path.with_suffix('.jpg') obviously returns a pathlib.PosixPath object (I'm on Linux) instead of my version of PosixPath, because I didn't redefine with_suffix. Do I have to copy everything from pathlib or is there a better way?

import os
import pathlib
from shutil import rmtree


class Path(pathlib.Path):

    def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        self = cls._from_parts(args, init=False)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        self._init()
        return self

    def with_stem(self, stem):
        """
        Return a new path with the stem changed.

        The stem is the final path component, minus its last suffix.
        """
        if not self.name:
            raise ValueError("%r has an empty name" % (self,))
        return self._from_parsed_parts(self._drv, self._root,
                                       self._parts[:-1] + [stem + self.suffix])

    def rmtree(self, ignore_errors=False, onerror=None):
        """
        Delete the entire directory even if it contains directories / files.
        """
        rmtree(str(self), ignore_errors, onerror)


class PosixPath(Path, pathlib.PurePosixPath):
    __slots__ = ()


class WindowsPath(Path, pathlib.PureWindowsPath):
    __slots__ = ()
1

There are 1 answers

1
ZZY On BEST ANSWER

Is some_path an instance of your version of Path?

I tested with the following 2 lines appended to your codes:

p = Path('test.foo')
print(type(p.with_suffix('.bar')))

Result is correct: <class '__main__.PosixPath'>

Only when using p = pathlib.Path('test.foo'), result is <class 'pathlib.PosixPath'>