Skip to content

Commit bdc3c88

Browse files
authored
GH-78722: Raise exceptions from pathlib.Path.iterdir() without delay. (#107320)
`pathlib.Path.iterdir()` now immediately raises any `OSError` exception from `os.listdir()`, rather than waiting until its result is iterated over.
1 parent 594b000 commit bdc3c88

File tree

3 files changed

+4
-3
lines changed

3 files changed

+4
-3
lines changed

Lib/pathlib.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,8 +1009,7 @@ def iterdir(self):
10091009
The children are yielded in arbitrary order, and the
10101010
special entries '.' and '..' are not included.
10111011
"""
1012-
for name in os.listdir(self):
1013-
yield self._make_child_relpath(name)
1012+
return (self._make_child_relpath(name) for name in os.listdir(self))
10141013

10151014
def _scandir(self):
10161015
# bpo-24132: a future version of pathlib will support subclassing of

Lib/test/test_pathlib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1766,7 +1766,7 @@ def test_iterdir_nodir(self):
17661766
# __iter__ on something that is not a directory.
17671767
p = self.cls(BASE, 'fileA')
17681768
with self.assertRaises(OSError) as cm:
1769-
next(p.iterdir())
1769+
p.iterdir()
17701770
# ENOENT or EINVAL under Windows, ENOTDIR otherwise
17711771
# (see issue #12802).
17721772
self.assertIn(cm.exception.errno, (errno.ENOTDIR,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix issue where :meth:`pathlib.Path.iterdir` did not raise :exc:`OSError`
2+
until iterated.

0 commit comments

Comments
 (0)