Repository navigation
Conversation
Implements the pathlib ABCs from pathlib-abc under the LittleFS.root property. These allow pathlib-like filesystem traversal. - pathlib-abc requires Python 3.9+ and should be upstreamed in core python in a future release. It provides most of the Pathlib API. - on Python 3.8 this API is unavailable. When Python 3.8 support is dropped, conditional/lazy imports can be cleaned up.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Introduction
I tested a few ways to implement the API as suggested in issue #172 and ended up settling on the pathlib-abc way. Here is the PR. While the PR isn't too complex, there a few design decisions. I captured the reasoning here, I feel many of them are a matter of choice and I'be happy to update the PR. The overall idea was to keep compatibility with the other littlefs APIs, but some things need changing the Pathlike API (caching). I'm sorry for the long description.
Overview
It is built on
pathlib-abc, the PyPI distribution of thepathlibABCs (JoinablePath/ReadablePath/WritablePath) that are being developed for CPython'spathlib. Implementing those ABCs meansglob,rglob,walk,copy,copy_into,read_text/write_textand the whole pure-path surface (parts,name,stem,suffix,parent,relative_to,full_match, ...) come for free fromiterdir()+info+ two open hooks, rather than being reimplemented here. However, this comes at a cost:A new dependency.
pathlib-abc>=0.5.2is added toinstall_requires. I've made it a conditional hard dependency (see the Python version note below), but I'm happy to move it to an extra (littlefs-python[pathlib]) if you'd rather not add a runtime dependency for everyone — the module already fails with a clearImportErrorwhen it's missing, so an extra would work without further changes.Python floor conflict.
pathlib-abcrequires Python 3.9+, but this package supports 3.8 (CI matrix,setup.pyclassifiers). I did not bump the floor. Instead:python_version >= '3.9';littlefs.pathis imported lazily, soimport littlefsstill works on 3.8 with nopathlib-abcinstalled, andLittleFS.root/ littlefs.LittleFSPathraise anImportError` explaining why;importorskiponpathlib_abc.If you'd prefer to drop 3.8 instead, this can be simplified considerably. Tested locally on CPython 3.8 (skips) and 3.9–3.14 (197 passed).
The API is provisional.
pathlib-abcis pre-1.0 and explicitly states its API "must be changed upstream in CPython", so this may need to follow breaking changes there. It already moved on me once during development, so a pin to a specific version instead of a floor may be in order.If this is too much of a limitation, I can post a previous version that didn't use it, but it's considerably more involved and I ended up abandoning it in favor of this solution. I think it's better, even if it has to wait until the stable release.
Design decisions
LittleFSPathis deliberately notos.PathLike.pathlib_abc.vfsopen()tries the builtinopen()first and falls back to__open_reader__onTypeError. If__fspath__were implemented,read_text()/write_bytes()would silently operate on the host filesystem instead of the image. There's a regression test for this. Consequence:os.fspath(path)andopen(path)don't work; usestr(path).__eq__/__hash__/ordering are implemented here. The ABCs deliberately omit them, butrelative_to(),is_relative_to()andcopy()'s distinct-path check all depend on__eq__— without itrelative_to()raisesValueError. The bound handle is part of the identity, so the same path string on two different images compares unequal; this is what makessrc.copy(other_fs.root / "same/path")work instead of being rejected as a self-copy.LittleFSPathInfoprovides_file_id.copy()refuses to copy a file onto itself, butpathlib_abc's helpers fall back to comparing paths when the info object cannot identify the file — not enough here, because littlefs resolves everything from the root, so"notes.txt"and"/notes.txt"are one file and two unequal paths. There are no inode numbers to report, so the normalized absolute path stands in, with the handle included so copies between images stay allowed. Note this is a private hook of a pre-1.0 package; if it goes away the behaviour degrades to the path comparison we had before, so nothing breaks loudly.PathInfois satisfied structurally, not inherited — as CPython's own_PathInfoBasedoes. Inheriting the protocol would drop__slots__(instances gain a__dict__), buy no static checking (pathlib-abcships nopy.typed, so the protocol isAnyto mypy and anAnybase makes the class more permissive), and not even catch a missing method, since protocol members carry trivial bodies rather than raising. Conformance is pinned by anisinstanceassertion in the tests instead.Both classes use
__slots__, because the ABCs are built for it:JoinablePath,ReadablePath,WritablePathandabc.ABCall declare__slots__ = (), so omitting it would put a__dict__back on every instance and waste that. It also keepsglob/walkcheap, which mint one path and one info per entry (measured ~15% less memory over 400 entries). The cost is thatfunctools.cached_propertyis unavailable, which is why theinfocache is hand-rolled.iterdir()translates errors and fails eagerly.LittleFSErroris not anOSError, so the ABC'sexcept OSErrorguards inglob()/walk()never fired and(fs.root / "file.txt").glob("*")raisedLFS_ERR_NOTDIRwherepathlibyields nothing.iterdir()now raisesNotADirectoryError/FileNotFoundError— matching whatopen(),mkdir()andremove()already do — and raises them at call time rather than on first iteration, because the globber builds a generator expression overiterdir()outside its owntryblock.iterdir()usesscandir(), notlistdir(), and primes each child'sinfowith the type it already learned, saving astat()per entry duringglob/walk. The listing is materialised before the first yield so the directory handle is closed and callers can mutate the tree while iterating.infocaches,exists()doesn't. ThePathInfoprotocol permits cached results and the ABC's glob/walk rely on it, soLittleFSPathInfocaches onestat(). Theexists()/is_file()/is_dir()methods on the path always do a fresh lookup, aspathlib.Pathdoes.Missing/existing paths are handled twice.
LittleFS.stat()raises a rawLittleFSError(-2)whilemkdir()/remove()/open()translate to builtins, so the code catches bothFileNotFoundError/FileExistsErrorandLittleFSErrorwith the matching code. If you'd rather translate consistently in theLittleFSmethods themselves, that would let this be simplified.rmdir()does not verify the target is a directory, becauseLittleFS.rmdiris an alias ofremoveand doesn't either. It therefore deletes a file, unlikepathlib.Path.rmdir. Kept consistent with the sibling API and documented; happy to add a check instead.No
match(). The ABCs providefull_match()(whole-path matching).pathlib's right-anchoredmatch()has subtle enough semantics that I'd rather not ship a near-miss; easy to add if you want it.littlefs has no symlinks, so
is_symlink()isFalseandreadlink()/symlink_to()raiseNotImplementedError. No mtimes either, sotouch()only creates missing files and never updates an existing one.Incidental changes
LittleFS.open()'sencoding/errors/newlineannotations changed fromstrtoOptional[str]. These were implicit-Optional, which PEP 484 disallows and mypy flags; the new call site made it visible. Signature-compatible.mypy.ini:ignore_missing_importsforpathlib_abc(it ships nopy.typed).Verification
pytest: 197 passed, 1 skipped on 3.9–3.14; 108 passed, 3 skipped on 3.8 (the 1 pre-existing skip is the Windows-only windisk test).black(23.12.0, the pinned pre-commit version,--line-length=120) andcodespellclean;mypy src/littlefs/path.pyclean.doc8unchanged.test_end_to_end_roundtripdrives a real filesystem: builds a tree, verifies it through the low-levelfs.listdir(), globs and reads it back, renames and unlinks, then tears the whole tree down through the path API.