Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4+: Extending pathlib.Path

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__ = ()
like image 967
Joschua Avatar asked Nov 15 '14 18:11

Joschua


People also ask

Which is better os path or pathlib?

With Pathlib, you can do all the basic file handling tasks that you did before, and there are some other features that don't exist in the OS module. The key difference is that Pathlib is more intuitive and easy to use. All the useful file handling methods belong to the Path objects.

What does path in pathlib do in Python?

Since Python 3.4, pathlib has been available in the standard library. With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together.

Is pathlib in standard library?

Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules.

How does the pathlib module represent paths?

The Pathlib module can deal with absolute as well as relative paths. An absolute path begins from the root directory and specifies the complete directory tree, whereas a relative path, as the name suggests, is the path of a file relative to another file or directory (usually the current directory).


1 Answers

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'>

like image 73
ZZY Avatar answered Oct 05 '22 02:10

ZZY