Skip to content

Commit e5f62ec

Browse files
committed
GH-119186: Slightly speed up os.walk(topdown=True)
When `os.walk()` traverses into subdirectories in top-down mode, call `os.path.join()` once to add a trailing slash, and use string concatenation thereafter to generate child paths.
1 parent 6239d41 commit e5f62ec

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

Lib/os.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -432,14 +432,16 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
432432
# Yield before sub-directory traversal if going top down
433433
yield top, dirs, nondirs
434434
# Traverse into sub-directories
435-
for dirname in reversed(dirs):
436-
new_path = join(top, dirname)
437-
# bpo-23605: os.path.islink() is used instead of caching
438-
# entry.is_symlink() result during the loop on os.scandir() because
439-
# the caller can replace the directory entry during the "yield"
440-
# above.
441-
if followlinks or not islink(new_path):
442-
stack.append(new_path)
435+
if dirs:
436+
prefix = join(top, top[:0]) # Add trailing slash
437+
for dirname in reversed(dirs):
438+
new_path = prefix + dirname
439+
# bpo-23605: os.path.islink() is used instead of caching
440+
# entry.is_symlink() result during the loop on os.scandir() because
441+
# the caller can replace the directory entry during the "yield"
442+
# above.
443+
if followlinks or not islink(new_path):
444+
stack.append(new_path)
443445
else:
444446
# Yield after sub-directory traversal if going bottom up
445447
stack.append((top, dirs, nondirs))
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Slightly speed up :func:`os.walk` by calling :func:`os.path.join` less
2+
often.

0 commit comments

Comments
 (0)