Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
21 changes: 17 additions & 4 deletions Doc/library/pathlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ Pure paths provide the following methods and properties:
True


.. method:: PurePath.relative_to(*other)
.. method:: PurePath.relative_to(*other, strict=True)

Compute a version of this path relative to the path represented by
*other*. If it's impossible, ValueError is raised::
Expand All @@ -549,12 +549,25 @@ Pure paths provide the following methods and properties:
>>> p.relative_to('/usr')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 694, in relative_to
.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute.
File "pathlib.py", line 941, in relative_to
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.
>>> p.relative_to('/usr', strict=False)
PurePosixPath('../etc/passwd')
>>> p.relative_to('foo', strict=False)
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.

If the path doesn't start with *other* and *strict* is ``True``, :exc:`ValueError` is raised. If *strict* is ``False`` and one path is relative and the other is absolute or if they reference different drives :exc:`ValueError` is raised.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the key difference should be spelled out in terms of whether adding .. entries is allowed. How about something like this?

In strict mode (the default), the path must start with *other*. In non-strict 
mode, ``..`` entries may be added to form the relative path. In all other 
cases, such as the paths referencing different drives, :exe:`ValueError` is 
raised.

.. warning::
    Non-strict mode assumes that no symlinks are present in the path; you 
    should call :meth:`~Path.resolve` first to ensure this.


NOTE: This function is part of :class:`PurePath` and works with strings. It does not check or access the underlying file structure.

.. versionadded:: 3.10
The *strict* argument (pre-3.10 behavior is strict).
Comment thread
domragusa marked this conversation as resolved.
Outdated


.. method:: PurePath.with_name(name)

Expand Down
30 changes: 22 additions & 8 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,10 +895,10 @@ def with_suffix(self, suffix):
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name])

def relative_to(self, *other):
def relative_to(self, *other, strict=True):
"""Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
related to the other path), raise ValueError.
Comment thread
domragusa marked this conversation as resolved.
"""
# For the purpose of this method, drive and root are considered
# separate parts, i.e.:
Expand All @@ -920,13 +920,27 @@ def relative_to(self, *other):
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):
common = 0
Comment thread
brettcannon marked this conversation as resolved.
Outdated
for p, tp in zip(cf(abs_parts), cf(to_abs_parts)):
Comment thread
brettcannon marked this conversation as resolved.
Outdated
if p != tp:
break
common += 1
if strict:
failure = (root or drv) if n == 0 else common != n
error_message = "{!r} is not in the subpath of {!r}"
up_parts = []
else:
failure = root != to_root
if drv or to_drv:
failure = cf([drv]) != cf([to_drv]) or (failure and n > 1)
error_message = "{!r} is not on the same drive as {!r}"
up_parts = (n-common)*['..']
error_message += " OR one path is relative and the other is absolute."
if failure:
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(error_message.format(str(self), str(formatted)))
Comment thread
brettcannon marked this conversation as resolved.
return self._from_parsed_parts('', root if common == 1 else '',
up_parts+abs_parts[common:])
Comment thread
domragusa marked this conversation as resolved.
Outdated

def is_relative_to(self, *other):
"""Return True if the path is relative to another path or False.
Expand Down
82 changes: 82 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,13 +613,29 @@ def test_relative_to_common(self):
self.assertEqual(p.relative_to('a/'), P('b'))
self.assertEqual(p.relative_to(P('a/b')), P())
self.assertEqual(p.relative_to('a/b'), P())
self.assertEqual(p.relative_to(P(), strict=False), P('a/b'))
self.assertEqual(p.relative_to('', strict=False), P('a/b'))
self.assertEqual(p.relative_to(P('a'), strict=False), P('b'))
self.assertEqual(p.relative_to('a', strict=False), P('b'))
self.assertEqual(p.relative_to('a/', strict=False), P('b'))
self.assertEqual(p.relative_to(P('a/b'), strict=False), P())
self.assertEqual(p.relative_to('a/b', strict=False), P())
self.assertEqual(p.relative_to(P('a/c'), strict=False), P('../b'))
self.assertEqual(p.relative_to('a/c', strict=False), P('../b'))
self.assertEqual(p.relative_to(P('a/b/c'), strict=False), P('..'))
self.assertEqual(p.relative_to('a/b/c', strict=False), P('..'))
self.assertEqual(p.relative_to(P('c'), strict=False), P('../a/b'))
self.assertEqual(p.relative_to('c', strict=False), P('../a/b'))
# With several args.
self.assertEqual(p.relative_to('a', 'b'), P())
self.assertEqual(p.relative_to('a', 'b', strict=False), P())
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P('c'))
self.assertRaises(ValueError, p.relative_to, P('a/b/c'))
self.assertRaises(ValueError, p.relative_to, P('a/c'))
self.assertRaises(ValueError, p.relative_to, P('/a'))
self.assertRaises(ValueError, p.relative_to, P('/'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('/a'), strict=False)
p = P('/a/b')
self.assertEqual(p.relative_to(P('/')), P('a/b'))
self.assertEqual(p.relative_to('/'), P('a/b'))
Expand All @@ -628,13 +644,28 @@ def test_relative_to_common(self):
self.assertEqual(p.relative_to('/a/'), P('b'))
self.assertEqual(p.relative_to(P('/a/b')), P())
self.assertEqual(p.relative_to('/a/b'), P())
self.assertEqual(p.relative_to(P('/'), strict=False), P('a/b'))
self.assertEqual(p.relative_to('/', strict=False), P('a/b'))
self.assertEqual(p.relative_to(P('/a'), strict=False), P('b'))
self.assertEqual(p.relative_to('/a', strict=False), P('b'))
self.assertEqual(p.relative_to('/a/', strict=False), P('b'))
self.assertEqual(p.relative_to(P('/a/b'), strict=False), P())
self.assertEqual(p.relative_to('/a/b', strict=False), P())
self.assertEqual(p.relative_to(P('/a/c'), strict=False), P('../b'))
self.assertEqual(p.relative_to('/a/c', strict=False), P('../b'))
self.assertEqual(p.relative_to(P('/a/b/c'), strict=False), P('..'))
self.assertEqual(p.relative_to('/a/b/c', strict=False), P('..'))
self.assertEqual(p.relative_to(P('/c'), strict=False), P('../a/b'))
self.assertEqual(p.relative_to('/c', strict=False), P('../a/b'))
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P('/c'))
self.assertRaises(ValueError, p.relative_to, P('/a/b/c'))
self.assertRaises(ValueError, p.relative_to, P('/a/c'))
self.assertRaises(ValueError, p.relative_to, P())
self.assertRaises(ValueError, p.relative_to, '')
self.assertRaises(ValueError, p.relative_to, P('a'))
self.assertRaises(ValueError, p.relative_to, P(''), strict=False)
self.assertRaises(ValueError, p.relative_to, P('a'), strict=False)

def test_is_relative_to_common(self):
P = self.cls
Expand Down Expand Up @@ -1079,6 +1110,16 @@ def test_relative_to(self):
self.assertEqual(p.relative_to('c:foO/'), P('Bar'))
self.assertEqual(p.relative_to(P('c:foO/baR')), P())
self.assertEqual(p.relative_to('c:foO/baR'), P())
self.assertEqual(p.relative_to(P('c:'), strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to('c:', strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to(P('c:foO'), strict=False), P('Bar'))
self.assertEqual(p.relative_to('c:foO', strict=False), P('Bar'))
self.assertEqual(p.relative_to('c:foO/', strict=False), P('Bar'))
self.assertEqual(p.relative_to(P('c:foO/baR'), strict=False), P())
self.assertEqual(p.relative_to('c:foO/baR', strict=False), P())
self.assertEqual(p.relative_to(P('C:Foo/Bar/Baz'), strict=False), P('..'))
self.assertEqual(p.relative_to(P('C:Foo/Baz'), strict=False), P('../Bar'))
self.assertEqual(p.relative_to(P('C:Baz/Bar'), strict=False), P('../../Foo/Bar'))
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P())
self.assertRaises(ValueError, p.relative_to, '')
Expand All @@ -1089,6 +1130,13 @@ def test_relative_to(self):
self.assertRaises(ValueError, p.relative_to, P('C:/Foo'))
self.assertRaises(ValueError, p.relative_to, P('C:Foo/Bar/Baz'))
self.assertRaises(ValueError, p.relative_to, P('C:Foo/Baz'))
self.assertRaises(ValueError, p.relative_to, P(), strict=False)
self.assertRaises(ValueError, p.relative_to, '', strict=False)
self.assertRaises(ValueError, p.relative_to, P('d:'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('/'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('/Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('C:/Foo'), strict=False)
p = P('C:/Foo/Bar')
self.assertEqual(p.relative_to(P('c:')), P('/Foo/Bar'))
self.assertEqual(p.relative_to('c:'), P('/Foo/Bar'))
Expand All @@ -1101,6 +1149,20 @@ def test_relative_to(self):
self.assertEqual(p.relative_to('c:/foO/'), P('Bar'))
self.assertEqual(p.relative_to(P('c:/foO/baR')), P())
self.assertEqual(p.relative_to('c:/foO/baR'), P())
self.assertEqual(p.relative_to(P('c:'), strict=False), P('/Foo/Bar'))
self.assertEqual(p.relative_to('c:', strict=False), P('/Foo/Bar'))
self.assertEqual(str(p.relative_to(P('c:'), strict=False)), '\\Foo\\Bar')
self.assertEqual(str(p.relative_to('c:', strict=False)), '\\Foo\\Bar')
self.assertEqual(p.relative_to(P('c:/'), strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to('c:/', strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to(P('c:/foO'), strict=False), P('Bar'))
self.assertEqual(p.relative_to('c:/foO', strict=False), P('Bar'))
self.assertEqual(p.relative_to('c:/foO/', strict=False), P('Bar'))
self.assertEqual(p.relative_to(P('c:/foO/baR'), strict=False), P())
self.assertEqual(p.relative_to('c:/foO/baR', strict=False), P())
self.assertEqual(p.relative_to('C:/Baz', strict=False), P('../Foo/Bar'))
self.assertEqual(p.relative_to('C:/Foo/Bar/Baz', strict=False), P('..'))
self.assertEqual(p.relative_to('C:/Foo/Baz', strict=False), P('../Bar'))
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P('C:/Baz'))
self.assertRaises(ValueError, p.relative_to, P('C:/Foo/Bar/Baz'))
Expand All @@ -1111,6 +1173,12 @@ def test_relative_to(self):
self.assertRaises(ValueError, p.relative_to, P('/'))
self.assertRaises(ValueError, p.relative_to, P('/Foo'))
self.assertRaises(ValueError, p.relative_to, P('//C/Foo'))
self.assertRaises(ValueError, p.relative_to, P('C:Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('d:'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('d:/'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('/'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('/Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('//C/Foo'), strict=False)
# UNC paths.
p = P('//Server/Share/Foo/Bar')
self.assertEqual(p.relative_to(P('//sErver/sHare')), P('Foo/Bar'))
Expand All @@ -1121,11 +1189,25 @@ def test_relative_to(self):
self.assertEqual(p.relative_to('//sErver/sHare/Foo/'), P('Bar'))
self.assertEqual(p.relative_to(P('//sErver/sHare/Foo/Bar')), P())
self.assertEqual(p.relative_to('//sErver/sHare/Foo/Bar'), P())
self.assertEqual(p.relative_to(P('//sErver/sHare'), strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to('//sErver/sHare', strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to('//sErver/sHare/', strict=False), P('Foo/Bar'))
self.assertEqual(p.relative_to(P('//sErver/sHare/Foo'), strict=False), P('Bar'))
self.assertEqual(p.relative_to('//sErver/sHare/Foo', strict=False), P('Bar'))
self.assertEqual(p.relative_to('//sErver/sHare/Foo/', strict=False), P('Bar'))
self.assertEqual(p.relative_to(P('//sErver/sHare/Foo/Bar'), strict=False), P())
self.assertEqual(p.relative_to('//sErver/sHare/Foo/Bar', strict=False), P())
self.assertEqual(p.relative_to(P('//sErver/sHare/bar'), strict=False), P('../Foo/Bar'))
self.assertEqual(p.relative_to('//sErver/sHare/bar', strict=False), P('../Foo/Bar'))
# Unrelated paths.
self.assertRaises(ValueError, p.relative_to, P('/Server/Share/Foo'))
self.assertRaises(ValueError, p.relative_to, P('c:/Server/Share/Foo'))
self.assertRaises(ValueError, p.relative_to, P('//z/Share/Foo'))
self.assertRaises(ValueError, p.relative_to, P('//Server/z/Foo'))
self.assertRaises(ValueError, p.relative_to, P('/Server/Share/Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('c:/Server/Share/Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('//z/Share/Foo'), strict=False)
self.assertRaises(ValueError, p.relative_to, P('//Server/z/Foo'), strict=False)

def test_is_relative_to(self):
P = self.cls
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,7 @@ Pierre Quentel
Brian Quinlan
Anders Qvist
Thomas Rachel
Domenico Ragusa
Ram Rachum
Jeffrey Rackauckas
Jérôme Radix
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add strict argument in :meth:`pathlib.PurePath.relative_to`.