Visitar URL original
gh-78707: deprecate passing >1 argument to `PurePath.[is_]relative_to()` by barneygale · Pull Request #94469 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Merge branch 'main' into gh-78707-pathlib-relative-to-arguments
  • Loading branch information
barneygale committed Nov 25, 2022
commit 0e79a853ac867e49fd4a1b841b50162bd2d839ca
27 changes: 23 additions & 4 deletions Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ Pure paths provide the following methods and properties:
True


.. method:: PurePath.relative_to(other)
.. method:: PurePath.relative_to(other, walk_up=False)

Compute a version of this path relative to the path represented by
*other*. If it's impossible, :exc:`ValueError` is raised::
Expand All @@ -585,10 +585,29 @@ Pure paths provide the following methods and properties:
raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.

.. note:
When *walk_up* is False (the default), the path must start with *other*.
When the argument is True, ``..`` entries may be added to form the
relative path. In all other cases, such as the paths referencing
different drives, :exc:`ValueError` is raised.::

This function is part of :class:`PurePath` and works with strings. It
does not access the filesystem.
>>> p.relative_to('/usr', walk_up=True)
PurePosixPath('../etc/passwd')
>>> p.relative_to('foo', walk_up=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 941, in relative_to
raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.

.. warning::
This function is part of :class:`PurePath` and works with strings.
It does not check or access the underlying file structure.
This can impact the *walk_up* option as it assumes that no symlinks
are present in the path; call :meth:`~Path.resolve` first if
necessary to resolve symlinks.

.. versionadded:: 3.12
The *walk_up* argument (old behavior is the same as ``walk_up=False``).

.. deprecated:: 3.12
Comment thread
barneygale marked this conversation as resolved.
Outdated

Expand Down
52 changes: 18 additions & 34 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,44 +624,31 @@ def with_suffix(self, suffix):
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name])

def relative_to(self, other, /, *_deprecated):
def relative_to(self, other, /, *_deprecated, walk_up=False):
"""Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
related to the other path), raise ValueError.

The *walk_up* parameter controls whether `..` may be used to resolve
the path.
"""
# For the purpose of this method, drive and root are considered
# separate parts, i.e.:
# Path('c:/').relative_to('c:') gives Path('/')
# Path('c:/').relative_to('/') raise ValueError
if _deprecated:
warnings.warn("support for supplying more than one argument to "
"pathlib.PurePath.relative_to() is deprecated and "
"scheduled for removal in Python 3.14.",
warnings.warn("support for supplying more than one positional "
"argument to pathlib.PurePath.relative_to() is "
"deprecated and scheduled for removal in Python "
"3.14.",
DeprecationWarning, stacklevel=2)
parts = self._parts
drv = self._drv
root = self._root
if root:
abs_parts = [drv, root] + parts[1:]
path_cls = type(self)
other = path_cls(other, *_deprecated)
for step, path in enumerate([other] + list(other.parents)):
if self.is_relative_to(path):
break
else:
abs_parts = parts
to_drv, to_root, to_parts = self._parse_args((other,) + _deprecated)
if to_root:
to_abs_parts = [to_drv, to_root] + to_parts[1:]
else:
to_abs_parts = to_parts
n = len(to_abs_parts)
cf = self._flavour.casefold_parts
if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts):
formatted = self._format_parsed_parts(to_drv, to_root, to_parts)
raise ValueError("{!r} is not in the subpath of {!r}"
" OR one path is relative and the other is absolute."
.format(str(self), str(formatted)))
return self._from_parsed_parts('', root if n == 1 else '',
abs_parts[n:])
raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
if step and not walk_up:
raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
parts = ('..',) * step + self.parts[len(path.parts):]
return path_cls(*parts)

def is_relative_to(self, other, /, *_deprecated):
"""Return True if the path is relative to another path or False.
Expand All @@ -671,12 +658,9 @@ def is_relative_to(self, other, /, *_deprecated):
"pathlib.PurePath.is_relative_to() is deprecated "
"and scheduled for removal in Python 3.14.",
DeprecationWarning, stacklevel=2)
other = self._from_parts((other,) + _deprecated)
try:
self.relative_to(other)
return True
except ValueError:
return False
other = type(self)(other, *_deprecated)
other = type(self)(other, *_deprecated)
return other == self or other in self.parents

@property
def parts(self):
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,8 @@ def test_relative_to_common(self):
# With several args.
with self.assertWarns(DeprecationWarning):
p.relative_to('a', 'b')
self.assertEqual(p.relative_to('a', 'b'), P())
self.assertEqual(p.relative_to('a', 'b', walk_up=True), P())
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P('c'))
self.assertRaises(ValueError, p.relative_to, P('a/b/c'))
Expand Down
You are viewing a condensed version of this merge commit. You can view the full changes here.