Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 46a3ba5

Browse files
committed
Simplify bottom-up implementation.
1 parent eb4b6ff commit 46a3ba5

1 file changed

Lines changed: 15 additions & 28 deletions

File tree

Lib/os.py

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,9 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
353353

354354
dirs = []
355355
nondirs = []
356-
walk_dirs = []
356+
if not topdown:
357+
# Yield after sub-directory traversal if going bottom up
358+
stack.append((top, dirs, nondirs))
357359

358360
# We may not have read permission for top, in which case we can't
359361
# get a list of the files the directory contains.
@@ -363,40 +365,31 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
363365
try:
364366
with scandir(top) as entries:
365367
for entry in entries:
368+
is_dir = False
366369
try:
367-
is_dir = entry.is_dir()
370+
if entry.is_dir():
371+
is_dir = True
372+
# Bottom-up: traverse into sub-directory, but exclude
373+
# symlinks to directories if followlinks is False
374+
if not topdown and (followlinks or not entry.is_symlink()):
375+
stack.append(entry.path)
368376
except OSError:
369377
# If is_dir() raises an OSError, consider the entry not to
370378
# be a directory, same behaviour as os.path.isdir().
371-
is_dir = False
379+
pass
372380

373381
if is_dir:
374382
dirs.append(entry.name)
375383
else:
376384
nondirs.append(entry.name)
377-
continue
378-
if topdown:
379-
continue
380385

381-
# Bottom-up: traverse into sub-directory, but exclude
382-
# symlinks to directories if followlinks is False
383-
if followlinks:
384-
walk_into = True
385-
else:
386-
try:
387-
is_symlink = entry.is_symlink()
388-
except OSError:
389-
# If is_symlink() raises an OSError, consider the
390-
# entry not to be a symbolic link, same behaviour
391-
# as os.path.islink().
392-
is_symlink = False
393-
walk_into = not is_symlink
394-
395-
if walk_into:
396-
walk_dirs.append(entry.path)
397386
except OSError as error:
398387
if onerror is not None:
399388
onerror(error)
389+
if not topdown:
390+
# Undo additions to stack.
391+
while not isinstance(stack.pop(), tuple):
392+
pass
400393
continue
401394

402395
if topdown:
@@ -413,12 +406,6 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
413406
# above.
414407
if followlinks or not islink(new_path):
415408
stack.append(new_path)
416-
else:
417-
# Yield after sub-directory traversal if going bottom up
418-
stack.append((top, dirs, nondirs))
419-
# Traverse into sub-directories
420-
for new_path in reversed(walk_dirs):
421-
stack.append(new_path)
422409

423410
__all__.append("walk")
424411

0 commit comments

Comments
 (0)