Skip to content

Commit d7cef7b

Browse files
authored
GH-111429: Speed up pathlib.PurePath.[is_]relative_to() (#111431)
1 parent b2af50c commit d7cef7b

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

Lib/pathlib.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -647,9 +647,11 @@ def relative_to(self, other, /, *_deprecated, walk_up=False):
647647
"scheduled for removal in Python {remove}")
648648
warnings._deprecated("pathlib.PurePath.relative_to(*args)", msg,
649649
remove=(3, 14))
650-
other = self.with_segments(other, *_deprecated)
650+
other = self.with_segments(other, *_deprecated)
651+
elif not isinstance(other, PurePath):
652+
other = self.with_segments(other)
651653
for step, path in enumerate([other] + list(other.parents)):
652-
if self.is_relative_to(path):
654+
if path == self or path in self.parents:
653655
break
654656
elif not walk_up:
655657
raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
@@ -658,7 +660,7 @@ def relative_to(self, other, /, *_deprecated, walk_up=False):
658660
else:
659661
raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
660662
parts = ['..'] * step + self._tail[len(path._tail):]
661-
return self.with_segments(*parts)
663+
return self._from_parsed_parts('', '', parts)
662664

663665
def is_relative_to(self, other, /, *_deprecated):
664666
"""Return True if the path is relative to another path or False.
@@ -669,7 +671,9 @@ def is_relative_to(self, other, /, *_deprecated):
669671
"scheduled for removal in Python {remove}")
670672
warnings._deprecated("pathlib.PurePath.is_relative_to(*args)",
671673
msg, remove=(3, 14))
672-
other = self.with_segments(other, *_deprecated)
674+
other = self.with_segments(other, *_deprecated)
675+
elif not isinstance(other, PurePath):
676+
other = self.with_segments(other)
673677
return other == self or other in self.parents
674678

675679
@property
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :meth:`pathlib.PurePath.relative_to` and
2+
:meth:`~pathlib.PurePath.is_relative_to`.

0 commit comments

Comments
 (0)