Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,14 +416,16 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
# Yield before sub-directory traversal if going top down
yield top, dirs, nondirs
# Traverse into sub-directories
for dirname in reversed(dirs):
new_path = join(top, dirname)
# bpo-23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
stack.append(new_path)
if dirs:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How much of the gain is due to the elimination of os.join and how much due to the check on empty dirs? On my system a walk of a folder with github repositories (including the cpython repo) has dirs empty about 60% of the times.

prefix = join(top, top[:0]) # Add trailing slash
for dirname in reversed(dirs):
new_path = prefix + dirname
# bpo-23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
stack.append(new_path)
else:
# Yield after sub-directory traversal if going bottom up
stack.append((top, dirs, nondirs))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Slightly speed up :func:`os.walk` by calling :func:`os.path.join` less
often.