Skip to content

gh-89727: Improve os.walk complexity and speed #100671

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 6 additions & 6 deletions Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,11 +341,11 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
"""
sys.audit("os.walk", top, topdown, onerror, followlinks)

stack = [(False, fspath(top))]
stack = [fspath(top)]
islink, join = path.islink, path.join
while stack:
must_yield, top = stack.pop()
if must_yield:
top = stack.pop()
if isinstance(top, tuple):
yield top
continue

Expand Down Expand Up @@ -422,13 +422,13 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
stack.append((False, new_path))
stack.append(new_path)
else:
# Yield after sub-directory traversal if going bottom up
stack.append((True, (top, dirs, nondirs)))
stack.append((top, dirs, nondirs))
# Traverse into sub-directories
for new_path in reversed(walk_dirs):
stack.append((False, new_path))
stack.append(new_path)

__all__.append("walk")

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Simplify and optimize :func:`os.walk` by using :func:`isinstance` checks to check the top of the stack.