Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b19ad11

Browse files
GH-119169: Slightly speed up os.walk(topdown=True) (GH-121431)
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 984d928 commit b19ad11

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
@@ -417,14 +417,16 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
417417
# Yield before sub-directory traversal if going top down
418418
yield top, dirs, nondirs
419419
# Traverse into sub-directories
420-
for dirname in reversed(dirs):
421-
new_path = join(top, dirname)
422-
# bpo-23605: os.path.islink() is used instead of caching
423-
# entry.is_symlink() result during the loop on os.scandir() because
424-
# the caller can replace the directory entry during the "yield"
425-
# above.
426-
if followlinks or not islink(new_path):
427-
stack.append(new_path)
420+
if dirs:
421+
prefix = join(top, top[:0]) # Add trailing slash
422+
for dirname in reversed(dirs):
423+
new_path = prefix + dirname
424+
# bpo-23605: os.path.islink() is used instead of caching
425+
# entry.is_symlink() result during the loop on os.scandir() because
426+
# the caller can replace the directory entry during the "yield"
427+
# above.
428+
if followlinks or not islink(new_path):
429+
stack.append(new_path)
428430
else:
429431
# Yield after sub-directory traversal if going bottom up
430432
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)

AltStyle によって変換されたページ (->オリジナル) /