diff options
author | Barney Gale <barney.gale@gmail.com> | 2023-12-04 23:21:39 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-12-04 23:21:39 (GMT) |
commit | 304a1b3f3a8ed9a734ef1d098cafccb6725162db (patch) | |
tree | 1e383edf3800521666f57883168260e4f964c46b | |
parent | 9fe7655c6ce0b8e9adc229daf681b6d30e6b1610 (diff) | |
download | cpython-304a1b3f3a8ed9a734ef1d098cafccb6725162db.zip cpython-304a1b3f3a8ed9a734ef1d098cafccb6725162db.tar.gz cpython-304a1b3f3a8ed9a734ef1d098cafccb6725162db.tar.bz2 |
GH-112727: Speed up `pathlib.Path.absolute()` (#112728)
Use `_from_parsed_parts()` to create a pre-joined/pre-parsed path, rather
than passing multiple arguments to `with_segments()`
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
-rw-r--r-- | Lib/pathlib.py | 20 | ||||
-rw-r--r-- | Misc/NEWS.d/next/Library/2023-12-04-21-30-34.gh-issue-112727.jpgNRB.rst | 1 |
2 files changed, 15 insertions, 6 deletions
diff --git a/Lib/pathlib.py b/Lib/pathlib.py index b728a0b..c48cff3 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -1415,21 +1415,29 @@ class Path(_PathBase): """ if self.is_absolute(): return self - elif self.drive: + if self.root: + drive = os.path.splitroot(os.getcwd())[0] + return self._from_parsed_parts(drive, self.root, self._tail) + if self.drive: # There is a CWD on each drive-letter drive. cwd = os.path.abspath(self.drive) else: cwd = os.getcwd() + if not self._tail: # Fast path for "empty" paths, e.g. Path("."), Path("") or Path(). # We pass only one argument to with_segments() to avoid the cost # of joining, and we exploit the fact that getcwd() returns a # fully-normalized string by storing it in _str. This is used to # implement Path.cwd(). - if not self.root and not self._tail: - result = self.with_segments(cwd) - result._str = cwd - return result - return self.with_segments(cwd, self) + result = self.with_segments(cwd) + result._str = cwd + return result + drive, root, rel = os.path.splitroot(cwd) + if not rel: + return self._from_parsed_parts(drive, root, self._tail) + tail = rel.split(self.pathmod.sep) + tail.extend(self._tail) + return self._from_parsed_parts(drive, root, tail) def resolve(self, strict=False): """ diff --git a/Misc/NEWS.d/next/Library/2023-12-04-21-30-34.gh-issue-112727.jpgNRB.rst b/Misc/NEWS.d/next/Library/2023-12-04-21-30-34.gh-issue-112727.jpgNRB.rst new file mode 100644 index 0000000..bbe7aae --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-12-04-21-30-34.gh-issue-112727.jpgNRB.rst @@ -0,0 +1 @@ +Speed up :meth:`pathlib.Path.absolute`. Patch by Barney Gale. |