Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1e610fb

Browse files
authored
GH-113225: Speed up pathlib.Path.walk(top_down=False) (#113693)
Use `_make_child_entry()` rather than `_make_child_relpath()` to retrieve path objects for directories to visit. This saves the allocation of one path object per directory in user subclasses of `PathBase`, and avoids a second loop. This trick does not apply when walking top-down, because users can affect the walk by modifying *dirnames* in-place. A side effect of this change is that, in bottom-up mode, subdirectories of each directory are visited in reverse order, and that this order doesn't match that of the names in *dirnames*. I suspect this is fine as the order is arbitrary anyway.
1 parent 6313cdd commit 1e610fb

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

Lib/pathlib/_abc.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,8 @@ def walk(self, top_down=True, on_error=None, follow_symlinks=False):
820820
with scandir_obj as scandir_it:
821821
dirnames = []
822822
filenames = []
823+
if not top_down:
824+
paths.append((path, dirnames, filenames))
823825
for entry in scandir_it:
824826
try:
825827
is_dir = entry.is_dir(follow_symlinks=follow_symlinks)
@@ -828,16 +830,15 @@ def walk(self, top_down=True, on_error=None, follow_symlinks=False):
828830
is_dir = False
829831

830832
if is_dir:
833+
if not top_down:
834+
paths.append(path._make_child_entry(entry))
831835
dirnames.append(entry.name)
832836
else:
833837
filenames.append(entry.name)
834838

835839
if top_down:
836840
yield path, dirnames, filenames
837-
else:
838-
paths.append((path, dirnames, filenames))
839-
840-
paths += [path._make_child_relpath(d) for d in reversed(dirnames)]
841+
paths += [path._make_child_relpath(d) for d in reversed(dirnames)]
841842

842843
def absolute(self):
843844
"""Return an absolute version of this path
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :meth:`pathlib.Path.walk` by using :attr:`os.DirEntry.path` where
2+
possible.

0 commit comments

Comments
 (0)