mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
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>
This commit is contained in:
parent
9fe7655c6c
commit
304a1b3f3a
2 changed files with 15 additions and 6 deletions
|
@ -1415,21 +1415,29 @@ class Path(_PathBase):
|
||||||
"""
|
"""
|
||||||
if self.is_absolute():
|
if self.is_absolute():
|
||||||
return self
|
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.
|
# There is a CWD on each drive-letter drive.
|
||||||
cwd = os.path.abspath(self.drive)
|
cwd = os.path.abspath(self.drive)
|
||||||
else:
|
else:
|
||||||
cwd = os.getcwd()
|
cwd = os.getcwd()
|
||||||
|
if not self._tail:
|
||||||
# Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
|
# Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
|
||||||
# We pass only one argument to with_segments() to avoid the cost
|
# We pass only one argument to with_segments() to avoid the cost
|
||||||
# of joining, and we exploit the fact that getcwd() returns a
|
# of joining, and we exploit the fact that getcwd() returns a
|
||||||
# fully-normalized string by storing it in _str. This is used to
|
# fully-normalized string by storing it in _str. This is used to
|
||||||
# implement Path.cwd().
|
# implement Path.cwd().
|
||||||
if not self.root and not self._tail:
|
result = self.with_segments(cwd)
|
||||||
result = self.with_segments(cwd)
|
result._str = cwd
|
||||||
result._str = cwd
|
return result
|
||||||
return result
|
drive, root, rel = os.path.splitroot(cwd)
|
||||||
return self.with_segments(cwd, self)
|
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):
|
def resolve(self, strict=False):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Speed up :meth:`pathlib.Path.absolute`. Patch by Barney Gale.
|
Loading…
Add table
Add a link
Reference in a new issue