]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-89727: Improve os.walk complexity (#100671)
authorStanislav Zmiev <zertarx@gmail.com>
Mon, 2 Jan 2023 21:41:19 +0000 (01:41 +0400)
committerGitHub <noreply@github.com>
Mon, 2 Jan 2023 21:41:19 +0000 (13:41 -0800)
Lib/os.py
Misc/NEWS.d/next/Library/2023-01-01-23-57-00.gh-issue-89727.ojedHN.rst [new file with mode: 0644]

index 73a5442ee8b83fda091671c77bed048b3c199de7..598c9e502301f759904cdcb830232d9b3fa84041 100644 (file)
--- a/Lib/os.py
+++ b/Lib/os.py
@@ -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
 
@@ -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")
 
diff --git a/Misc/NEWS.d/next/Library/2023-01-01-23-57-00.gh-issue-89727.ojedHN.rst b/Misc/NEWS.d/next/Library/2023-01-01-23-57-00.gh-issue-89727.ojedHN.rst
new file mode 100644 (file)
index 0000000..38c0d5c
--- /dev/null
@@ -0,0 +1 @@
+Simplify and optimize :func:`os.walk` by using :func:`isinstance` checks to check the top of the stack.