Skip to content

GH-119169: Speed up os.fwalk(topdown=False) #121433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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-119169: Speed up os.fwalk(topdown=False)
Add entries to the stack while iterating over `os.scandir()` results,
rather than afterwards. This removes the need for an `entries` list and
some zipping.
  • Loading branch information
barneygale committed Jul 6, 2024
commit bedf76e95d4609af3bf6df92ee7f54b30f36eebb
23 changes: 10 additions & 13 deletions Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,16 +542,22 @@ def _fwalk(stack, isbytes, topdown, onerror, follow_symlinks):
scandir_it = scandir(topfd)
dirs = []
nondirs = []
entries = None if topdown or follow_symlinks else []
topprefix = path.join(toppath, toppath[:0]) # Add trailing slash.
if not topdown:
# Yield after sub-directory traversal if going bottom up.
stack.append((_fwalk_yield, (toppath, dirs, nondirs, topfd)))
for entry in scandir_it:
name = entry.name
if isbytes:
name = fsencode(name)
try:
if entry.is_dir():
dirs.append(name)
if entries is not None:
entries.append(entry)
if not topdown:
stack.append(
(_fwalk_walk, (
False, topfd, topprefix + name, name,
None if follow_symlinks else entry)))
else:
nondirs.append(name)
except OSError:
Expand All @@ -564,18 +570,9 @@ def _fwalk(stack, isbytes, topdown, onerror, follow_symlinks):

if topdown:
yield toppath, dirs, nondirs, topfd
else:
stack.append((_fwalk_yield, (toppath, dirs, nondirs, topfd)))

toppath = path.join(toppath, toppath[:0]) # Add trailing slash.
if entries is None:
stack.extend(
(_fwalk_walk, (False, topfd, toppath + name, name, None))
(_fwalk_walk, (False, topfd, topprefix + name, name, None))
for name in dirs[::-1])
else:
stack.extend(
(_fwalk_walk, (False, topfd, toppath + name, name, entry))
for name, entry in zip(dirs[::-1], entries[::-1]))

__all__.append("fwalk")

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up :func:`os.fwalk` in bottom-up mode.
Loading