Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
GH-117727: Speed up pathlib.Path.iterdir() by using os.scandir()
Replace use of `os.listdir()` with `os.scandir()`. Forgo setting `_drv`,
`_root` and `_tail_cached`, as these usually aren't needed. Use
`os.DirEntry.path` to set `_str`.
  • Loading branch information
barneygale committed Apr 10, 2024
commit 84534f9df17f8134b0329e43a8cb5d16f9551835
25 changes: 6 additions & 19 deletions Lib/pathlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,12 @@ def iterdir(self):
The children are yielded in arbitrary order, and the
special entries '.' and '..' are not included.
"""
return (self._make_child_relpath(name) for name in os.listdir(self))
root_dir = str(self)
with os.scandir(root_dir) as scandir_it:
paths = [entry.path for entry in scandir_it]
Comment thread
barneygale marked this conversation as resolved.
if root_dir == '.':
paths = map(self._remove_leading_dot, paths)
return map(self._from_parsed_string, paths)

def _scandir(self):
return os.scandir(self)
Expand All @@ -599,24 +604,6 @@ def _make_child_direntry(self, entry):
path._tail_cached = self._tail + [entry.name]
return path

def _make_child_relpath(self, name):
if not name:
return self
path_str = str(self)
tail = self._tail
if tail:
path_str = f'{path_str}{self.parser.sep}{name}'
elif path_str != '.':
path_str = f'{path_str}{name}'
else:
path_str = name
path = self.with_segments(path_str)
path._str = path_str
path._drv = self.drive
path._root = self.root
path._tail_cached = tail + [name]
return path

def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
"""Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given relative pattern.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :meth:`pathlib.Path.iterdir` by using :func:`os.scandir`
internally.