Skip to content

Commit

Permalink
pythonGH-112727: Speed up pathlib.Path.absolute()
Browse files Browse the repository at this point in the history
Use `_from_parsed_parts()` to create a pre-joined/pre-parsed path, rather
than passing multiple arguments to `with_segments()`
  • Loading branch information
barneygale committed Dec 4, 2023
1 parent 09505c5 commit b827144
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
35 changes: 21 additions & 14 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1415,21 +1415,28 @@ def absolute(self):
"""
if self.is_absolute():
return self
elif self.drive:
# There is a CWD on each drive-letter drive.
cwd = os.path.abspath(self.drive)
else:
elif self.root:
cwd = os.getcwd()
# 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)
if self._tail:
cwd_drv = os.path.splitroot(cwd)[0]
return self._from_parsed_parts(cwd_drv, self.root, self._tail)
else:
cwd = os.path.abspath(self.drive) if self.drive else os.getcwd()
if self._tail:
# Optimization: use os.path.splitroot() rather than _parse_path().
# This is possible because os.getcwd() returns a normalized path.
cwd_drv, cwd_root, cwd_tail = os.path.splitroot(cwd)
if cwd_tail:
cwd_tail = cwd_tail.split(self.pathmod.sep)
cwd_tail.extend(self._tail)
else:
cwd_tail = self._tail
return self._from_parsed_parts(cwd_drv, cwd_root, cwd_tail)
# Optimization: store the result of os.getcwd() as the normalized
# string representation of the path.
result = self.with_segments(cwd)
result._str = cwd
return result

def resolve(self, strict=False):
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up :meth:`pathlib.Path.absolute`. Patch by Barney Gale.

0 comments on commit b827144

Please sign in to comment.