mirror of
https://github.com/python/cpython.git
synced 2025-09-27 02:39:58 +00:00
gh-89727: Improve os.walk complexity (#100671)
This commit is contained in:
parent
d7e7f79ca7
commit
73097d91a6
2 changed files with 7 additions and 6 deletions
12
Lib/os.py
12
Lib/os.py
|
@ -341,11 +341,11 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
|
||||||
"""
|
"""
|
||||||
sys.audit("os.walk", top, topdown, onerror, followlinks)
|
sys.audit("os.walk", top, topdown, onerror, followlinks)
|
||||||
|
|
||||||
stack = [(False, fspath(top))]
|
stack = [fspath(top)]
|
||||||
islink, join = path.islink, path.join
|
islink, join = path.islink, path.join
|
||||||
while stack:
|
while stack:
|
||||||
must_yield, top = stack.pop()
|
top = stack.pop()
|
||||||
if must_yield:
|
if isinstance(top, tuple):
|
||||||
yield top
|
yield top
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
@ -422,13 +422,13 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
|
||||||
# the caller can replace the directory entry during the "yield"
|
# the caller can replace the directory entry during the "yield"
|
||||||
# above.
|
# above.
|
||||||
if followlinks or not islink(new_path):
|
if followlinks or not islink(new_path):
|
||||||
stack.append((False, new_path))
|
stack.append(new_path)
|
||||||
else:
|
else:
|
||||||
# Yield after sub-directory traversal if going bottom up
|
# Yield after sub-directory traversal if going bottom up
|
||||||
stack.append((True, (top, dirs, nondirs)))
|
stack.append((top, dirs, nondirs))
|
||||||
# Traverse into sub-directories
|
# Traverse into sub-directories
|
||||||
for new_path in reversed(walk_dirs):
|
for new_path in reversed(walk_dirs):
|
||||||
stack.append((False, new_path))
|
stack.append(new_path)
|
||||||
|
|
||||||
__all__.append("walk")
|
__all__.append("walk")
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Simplify and optimize :func:`os.walk` by using :func:`isinstance` checks to check the top of the stack.
|
Loading…
Add table
Add a link
Reference in a new issue