# HG changeset patch # User Franz Glasner # Date 1736594411 -3600 # Node ID 506d895a850003f29f2af2b18331f34d2118427b # Parent fc1055878775d5b596105b00fa653931e5b12576 Implement cutils.util.walk.Scandir as a wrapper for os.scandir() diff -r fc1055878775 -r 506d895a8500 cutils/util/walk.py --- a/cutils/util/walk.py Fri Jan 10 15:34:50 2025 +0100 +++ b/cutils/util/walk.py Sat Jan 11 12:20:11 2025 +0100 @@ -220,6 +220,36 @@ # Yield after recursion if going bottom up yield top, fsobjects + + class ScanDir(object): # noqa: E303 too many blank lines + + """An :func:`os.scandir` wrapper that is always an iterator and + a context manager. + + """ + + __slots__ = ("_scandir_it", ) + + def __init__(self, path): + super(ScanDir, self).__init__() + self._scandir_it = os.scandir(path) + + def __iter__(self): + return self + + def __next__(self): + return WalkDirEntry.from_direntry(next(self._scandir_it)) + + if PY2: + next = __next__ + + def __enter__(self): + return self + + def __exit__(self, *args, **kwds): + if hasattr(self._scandir_it, "close"): + self._scandir_it.close() + else: def _walk(root, top, follow_symlinks): @@ -260,3 +290,34 @@ yield from _walk(root, top + (wd.name,), follow_symlinks) # Yield after recursion if going bottom up yield top, fsobjects + + + class ScanDir(object): # noqa: E303 too many blank lines + + """An :func:`os.scandir` wrapper that is always an iterator and + a context manager. + + """ + + __slots__ = ("_listdir_it", "_path") + + def __init__(self, path): + super(ScanDir, self).__init__() + self._listdir_it = iter(os.listdir(path)) + self._path = path + + def __iter__(self): + return self + + def __next__(self): + return WalkDirEntry.from_path_name(self._path, + next(self._listdir_it)) + + if PY2: + next = __next__ + + def __enter__(self): + return self + + def __exit__(self, *args, **kwds): + pass