Skip to content

Commit 73097d9

Browse files
authored
gh-89727: Improve os.walk complexity (#100671)
1 parent d7e7f79 commit 73097d9

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

Lib/os.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -341,11 +341,11 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
341341
"""
342342
sys.audit("os.walk", top, topdown, onerror, followlinks)
343343

344-
stack = [(False, fspath(top))]
344+
stack = [fspath(top)]
345345
islink, join = path.islink, path.join
346346
while stack:
347-
must_yield, top = stack.pop()
348-
if must_yield:
347+
top = stack.pop()
348+
if isinstance(top, tuple):
349349
yield top
350350
continue
351351

@@ -422,13 +422,13 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
422422
# the caller can replace the directory entry during the "yield"
423423
# above.
424424
if followlinks or not islink(new_path):
425-
stack.append((False, new_path))
425+
stack.append(new_path)
426426
else:
427427
# Yield after sub-directory traversal if going bottom up
428-
stack.append((True, (top, dirs, nondirs)))
428+
stack.append((top, dirs, nondirs))
429429
# Traverse into sub-directories
430430
for new_path in reversed(walk_dirs):
431-
stack.append((False, new_path))
431+
stack.append(new_path)
432432

433433
__all__.append("walk")
434434

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

0 commit comments

Comments
 (0)