comparison cutils/util/walk.py @ 123:4a0c3c9eead7

Use the output of "scandir()" directly if it has a "close" method. Use a "nullcontext" otherwise.
author Franz Glasner <fzglas.hg@dom66.de>
date Thu, 02 Jan 2025 12:43:40 +0100
parents 2dc26a2f3d1c
children c7df81fb84b7
comparison
equal deleted inserted replaced
122:1e5127028254 123:4a0c3c9eead7
16 except ImportError: 16 except ImportError:
17 try: 17 try:
18 from scandir import scandir 18 from scandir import scandir
19 except ImportError: 19 except ImportError:
20 scandir = None 20 scandir = None
21 from contextlib import closing
22 21
23 from .cm import nullcontext 22 from .cm import nullcontext
24 from .constants import PY2 23 from .constants import PY2
25 24
26 25
155 else: 154 else:
156 path = root 155 path = root
157 156
158 dirs, nondirs, walk_dirs = [], [], [] 157 dirs, nondirs, walk_dirs = [], [], []
159 158
160 scandir_it = scandir(path) 159 scandir_cm = scandir(path)
161 if hasattr(scandir_it, "close"): 160 if not hasattr(scandir_cm, "close"):
162 scandir_ctx = closing(scandir_it) 161 scandir_cm = nullcontext(scandir_cm)
163 else: 162 with scandir_cm as scandir_it:
164 scandir_ctx = nullcontext(scandir_it)
165 with scandir_ctx as scandir_it:
166 while True: 163 while True:
167 try: 164 try:
168 entry = WalkDirEntry.from_direntry(next(scandir_it)) 165 entry = WalkDirEntry.from_direntry(next(scandir_it))
169 except StopIteration: 166 except StopIteration:
170 break 167 break