From bdc3c884cdc90102ad68b6b55dc9b988e729ae35 Mon Sep 17 00:00:00 2001 From: Barney Gale Date: Sat, 2 Sep 2023 16:08:03 +0100 Subject: [PATCH] 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. --- Lib/pathlib.py | 3 +-- Lib/test/test_pathlib.py | 2 +- .../next/Library/2023-07-26-22-52-48.gh-issue-78722.6SKBLt.rst | 2 ++ 3 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-07-26-22-52-48.gh-issue-78722.6SKBLt.rst diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 758f70f5ba7..f4ec315da6b 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -1009,8 +1009,7 @@ def iterdir(self): The children are yielded in arbitrary order, and the special entries '.' and '..' are not included. """ - for name in os.listdir(self): - yield self._make_child_relpath(name) + return (self._make_child_relpath(name) for name in os.listdir(self)) def _scandir(self): # bpo-24132: a future version of pathlib will support subclassing of diff --git a/Lib/test/test_pathlib.py b/Lib/test/test_pathlib.py index 74deec84336..09df3fe471f 100644 --- a/Lib/test/test_pathlib.py +++ b/Lib/test/test_pathlib.py @@ -1766,7 +1766,7 @@ def test_iterdir_nodir(self): # __iter__ on something that is not a directory. p = self.cls(BASE, 'fileA') with self.assertRaises(OSError) as cm: - next(p.iterdir()) + p.iterdir() # ENOENT or EINVAL under Windows, ENOTDIR otherwise # (see issue #12802). self.assertIn(cm.exception.errno, (errno.ENOTDIR, diff --git a/Misc/NEWS.d/next/Library/2023-07-26-22-52-48.gh-issue-78722.6SKBLt.rst b/Misc/NEWS.d/next/Library/2023-07-26-22-52-48.gh-issue-78722.6SKBLt.rst new file mode 100644 index 00000000000..aea26ee2f99 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-07-26-22-52-48.gh-issue-78722.6SKBLt.rst @@ -0,0 +1,2 @@ +Fix issue where :meth:`pathlib.Path.iterdir` did not raise :exc:`OSError` +until iterated.