Skip to content

Commit 9ba9f68

Browse files
mjbommarclaude
andcommitted
gh-151788: Address review — OSError fallback and tone down NEWS
- Wrap entry.is_dir()/is_symlink() in try/except OSError, falling back to False to exactly mirror os.path.isdir()/islink() (matches os.walk()). - Reword the NEWS entry to avoid speedup-multiplier claims; describe it as improving list_directory() on systems with slow stat calls. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 0606d02 commit 9ba9f68

2 files changed

Lines changed: 19 additions & 9 deletions

File tree

Lib/http/server.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -902,13 +902,22 @@ def list_directory(self, path):
902902
for entry in entries:
903903
name = entry.name
904904
displayname = linkname = name
905-
# Append / for directories or @ for symbolic links.
906-
# Use cached os.DirEntry methods to avoid a stat() per entry,
907-
# which is costly on network filesystems such as NFS.
908-
if entry.is_dir():
905+
# Append / for directories or @ for symbolic links. Use the cached
906+
# os.DirEntry methods to avoid a stat() per entry. Fall back to
907+
# False on OSError to mirror os.path.isdir()/islink(), whose result
908+
# would otherwise differ (e.g. a symlink to an unreadable target).
909+
try:
910+
is_dir = entry.is_dir()
911+
except OSError:
912+
is_dir = False
913+
try:
914+
is_symlink = entry.is_symlink()
915+
except OSError:
916+
is_symlink = False
917+
if is_dir:
909918
displayname = name + "/"
910919
linkname = name + "/"
911-
if entry.is_symlink():
920+
if is_symlink:
912921
displayname = name + "@"
913922
# Note: a link to a directory displays with @ and links with /
914923
r.append('<li><a href="%s">%s</a></li>'
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
Speed up :class:`http.server.SimpleHTTPRequestHandler` directory listings by
2-
using :func:`os.scandir` instead of :func:`os.listdir` plus an :func:`os.stat`
3-
call per entry. This is faster on all filesystems and especially on network
4-
filesystems such as NFS.
1+
:class:`http.server.SimpleHTTPRequestHandler` now builds directory listings
2+
with :func:`os.scandir` instead of :func:`os.listdir` followed by an
3+
:func:`os.stat` call per entry. This improves the performance of
4+
:meth:`~http.server.SimpleHTTPRequestHandler.list_directory` on systems with
5+
slow ``stat`` calls, such as network filesystems.

0 commit comments

Comments
 (0)