Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GH-103548: Improve performance of pathlib.Path.[is_]absolute() #103549

Merged
merged 10 commits into from
May 6, 2023
11 changes: 10 additions & 1 deletion Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ def is_absolute(self):
# ntpath.isabs() is defective - see GH-44626 .
if self._flavour is ntpath:
return bool(self.drive and self.root)
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
return self._flavour.isabs(self)
return self._flavour.isabs(self._raw_path)

def is_reserved(self):
"""Return True if the path contains one of the special names reserved
Expand Down Expand Up @@ -873,6 +873,15 @@ def absolute(self):
cwd = self._flavour.abspath(self.drive)
else:
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:
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
result = self.with_segments(cwd)
result._str = cwd
return result
return self.with_segments(cwd, self)

def resolve(self, strict=False):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Improve performance of :meth:`pathlib.Path.absolute` and
:meth:`~pathlib.Path.cwd` by joining paths only when necessary. Also improve
performance of :meth:`pathlib.PurePath.is_absolute` on Posix by skipping path
parsing and normalization.