Skip to content

Commit 371c970

Browse files
authored
gh-114709: Fix exceptions raised by posixpath.commonpath (#114710)
Fix the exceptions raised by posixpath.commonpath Raise ValueError, not IndexError when passed an empty iterable. Raise TypeError, not ValueError when passed None.
1 parent f9154f8 commit 371c970

File tree

4 files changed

+11
-3
lines changed

4 files changed

+11
-3
lines changed

Doc/library/os.path.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ the :mod:`glob` module.)
7979

8080
.. function:: commonpath(paths)
8181

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

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

9595

9696
.. function:: commonprefix(list)

Lib/posixpath.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -546,10 +546,11 @@ def relpath(path, start=None):
546546
def commonpath(paths):
547547
"""Given a sequence of path names, returns the longest common sub-path."""
548548

549+
paths = tuple(map(os.fspath, paths))
550+
549551
if not paths:
550552
raise ValueError('commonpath() arg is an empty sequence')
551553

552-
paths = tuple(map(os.fspath, paths))
553554
if isinstance(paths[0], bytes):
554555
sep = b'/'
555556
curdir = b'.'

Lib/test/test_posixpath.py

+2
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,9 @@ def check_error(exc, paths):
703703
self.assertRaises(exc, posixpath.commonpath,
704704
[os.fsencode(p) for p in paths])
705705

706+
self.assertRaises(TypeError, posixpath.commonpath, None)
706707
self.assertRaises(ValueError, posixpath.commonpath, [])
708+
self.assertRaises(ValueError, posixpath.commonpath, iter([]))
707709
check_error(ValueError, ['/usr', 'usr'])
708710
check_error(ValueError, ['usr', '/usr'])
709711

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:func:`posixpath.commonpath()` now raises a :exc:`ValueError` exception when
2+
passed an empty iterable. Previously, :exc:`IndexError` was raised.
3+
4+
:func:`posixpath.commonpath()` now raises a :exc:`TypeError` exception when
5+
passed ``None``. Previously, :exc:`ValueError` was raised.

0 commit comments

Comments
 (0)