Skip to content

Commit

Permalink
pythongh-114709: Fix exceptions raised by posixpath.commonpath (pytho…
Browse files Browse the repository at this point in the history
…n#114710)

Fix the exceptions raised by posixpath.commonpath

Raise ValueError, not IndexError when passed an empty iterable. Raise
TypeError, not ValueError when passed None.
  • Loading branch information
srittau authored and diegorusso committed Apr 17, 2024
1 parent 3f47339 commit 033f5d5
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 3 deletions.
4 changes: 2 additions & 2 deletions Doc/library/os.path.rst
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ the :mod:`glob` module.)

.. function:: commonpath(paths)

Return the longest common sub-path of each pathname in the sequence
Return the longest common sub-path of each pathname in the iterable
*paths*. Raise :exc:`ValueError` if *paths* contain both absolute
and relative pathnames, the *paths* are on the different drives or
if *paths* is empty. Unlike :func:`commonprefix`, this returns a
Expand All @@ -90,7 +90,7 @@ the :mod:`glob` module.)
.. versionadded:: 3.5

.. versionchanged:: 3.6
Accepts a sequence of :term:`path-like objects <path-like object>`.
Accepts an iterable of :term:`path-like objects <path-like object>`.


.. function:: commonprefix(list)
Expand Down
3 changes: 2 additions & 1 deletion Lib/posixpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,10 +546,11 @@ def relpath(path, start=None):
def commonpath(paths):
"""Given a sequence of path names, returns the longest common sub-path."""

paths = tuple(map(os.fspath, paths))

if not paths:
raise ValueError('commonpath() arg is an empty sequence')

paths = tuple(map(os.fspath, paths))
if isinstance(paths[0], bytes):
sep = b'/'
curdir = b'.'
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_posixpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,9 @@ def check_error(exc, paths):
self.assertRaises(exc, posixpath.commonpath,
[os.fsencode(p) for p in paths])

self.assertRaises(TypeError, posixpath.commonpath, None)
self.assertRaises(ValueError, posixpath.commonpath, [])
self.assertRaises(ValueError, posixpath.commonpath, iter([]))
check_error(ValueError, ['/usr', 'usr'])
check_error(ValueError, ['usr', '/usr'])

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:func:`posixpath.commonpath()` now raises a :exc:`ValueError` exception when
passed an empty iterable. Previously, :exc:`IndexError` was raised.

:func:`posixpath.commonpath()` now raises a :exc:`TypeError` exception when
passed ``None``. Previously, :exc:`ValueError` was raised.

0 comments on commit 033f5d5

Please sign in to comment.