Skip to content

Commit cadb8ba

Browse files
delta87nicoddemus
authored andcommitted
Refactor scandir to use narrower try/except blocks and improve clarity
1 parent a14e8f6 commit cadb8ba

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

src/_pytest/pathlib.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -957,23 +957,26 @@ def scandir(
957957
The default is to sort by name.
958958
If the directory does not exist, return an empty list.
959959
"""
960+
entries = []
961+
# Attempt to create a scandir iterator for the given path.
960962
try:
961-
entries = []
962-
with os.scandir(path) as s:
963-
# Skip entries with symlink loops and other brokenness, so the caller
964-
# doesn't have to deal with it.
965-
for entry in s:
966-
try:
967-
entry.is_file()
968-
except OSError as err:
969-
if _ignore_error(err):
970-
continue
971-
raise
972-
entries.append(entry)
973-
entries.sort(key=sort_key) # type: ignore[arg-type]
974-
return entries
963+
scandir_iter = os.scandir(path)
975964
except FileNotFoundError:
965+
# If the directory does not exist, return an empty list.
976966
return []
967+
# Use the scandir iterator in a context manager to ensure it is properly closed.
968+
with scandir_iter as s:
969+
for entry in s:
970+
try:
971+
entry.is_file()
972+
except OSError as err:
973+
if _ignore_error(err):
974+
continue
975+
# Reraise non-ignorable errors to avoid hiding issues.
976+
raise
977+
entries.append(entry)
978+
entries.sort(key=sort_key) # type: ignore[arg-type]
979+
return entries
977980

978981

979982
def visit(

0 commit comments

Comments
 (0)