From 4d552aa6c22974919e2d05c0e59092094ef95928 Mon Sep 17 00:00:00 2001 From: barneygale Date: Wed, 26 Jul 2023 22:53:07 +0100 Subject: [PATCH] GH-78722: Raise exceptions from `pathlib.Path.iterdir()` without delay. `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 8ff4d4ea19168f..d61e7e89cb5999 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -1007,8 +1007,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 78948e3b720320..5401c7242e98b5 100644 --- a/Lib/test/test_pathlib.py +++ b/Lib/test/test_pathlib.py @@ -1754,7 +1754,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 00000000000000..aea26ee2f99467 --- /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.