I’m not sure what expectations about objects you’re referring to, but I think it’s entirely viable and makes perfect sense to add the stats caching performed by os.scandir into the Path objects, since those os.DirEntry objects that os.scandir generates have direct 1-to-1 corresponding methods in Path objects.
To quote the documentation of os.DirEntry:
Note that there is a nice correspondence between several attributes and methods of
os.DirEntryand ofpathlib.Path. In particular, thenameattribute has the same meaning, as do theis_dir(),is_file(),is_symlink(),is_junction(), andstat()methods.
Here’s a quick implementation of a scandir method for a Path object that generates Path objects instead of os.DirEntry objects:
import os
from pathlib import WindowsPath, PosixPath
class ScannablePath(WindowsPath if os.name == 'nt' else PosixPath):
def scandir(self):
yield from map(CachedPath, os.scandir(self))
class CachedPath(ScannablePath):
def __new__(cls, dir_entry):
path = super().__new__(cls, dir_entry.path)
path._dir_entry = dir_entry
return path
is_dir = lambda self: self._dir_entry.is_dir()
is_file = lambda self: self._dir_entry.is_file()
is_symlink = lambda self: self._dir_entry.is_symlink()
is_junction = lambda self: self._dir_entry.is_junction()
stat = lambda self: self._dir_entry.stat()
for path in ScannablePath('/').scandir():
print(path.name, path.is_dir(), path.stat().st_size)
Demo here