Skip to content

Pathlib-like API via pathlib-abc - #185

Open
Krakonos wants to merge 3 commits into
jrast:masterfrom
Krakonos:pathlib-abc-paths-v2
Open

Krakonos wants to merge 3 commits into
jrast:masterfrom
Krakonos:pathlib-abc-paths-v2

Conversation

@Krakonos

Copy link
Copy Markdown
Contributor

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 the pathlib ABCs (JoinablePath / ReadablePath / WritablePath) that are being developed for CPython's pathlib. Implementing those ABCs means glob, rglob, walk, copy, copy_into, read_text/write_text and the whole pure-path surface (parts, name, stem, suffix, parent, relative_to, full_match, ...) come for free from iterdir() + info + two open hooks, rather than being reimplemented here. However, this comes at a cost:

A new dependency. pathlib-abc>=0.5.2 is added to install_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 clear ImportError when it's missing, so an extra would work without further changes.

Python floor conflict. pathlib-abc requires Python 3.9+, but this package supports 3.8 (CI matrix, setup.py classifiers). I did not bump the floor. Instead:

  • the dependency is marked python_version >= '3.9';
  • littlefs.path is imported lazily, so import littlefs still works on 3.8 with no pathlib-abc installed, and LittleFS.root / littlefs.LittleFSPathraise anImportError` explaining why;
  • the two new test modules importorskip on pathlib_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-abc is 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

  • LittleFSPath is deliberately not os.PathLike. pathlib_abc.vfsopen() tries the builtin open() first and falls back to __open_reader__ on TypeError. 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) and open(path) don't work; use str(path).

  • __eq__/__hash__/ordering are implemented here. The ABCs deliberately omit them, but relative_to(), is_relative_to() and copy()'s distinct-path check all depend on __eq__ — without it relative_to() raises ValueError. The bound handle is part of the identity, so the same path string on two different images compares unequal; this is what makes src.copy(other_fs.root / "same/path") work instead of being rejected as a self-copy.

  • LittleFSPathInfo provides _file_id. copy() refuses to copy a file onto itself, but pathlib_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.

  • PathInfo is satisfied structurally, not inherited — as CPython's own _PathInfoBase does. Inheriting the protocol would drop __slots__ (instances gain a __dict__), buy no static checking (pathlib-abc ships no py.typed, so the protocol is Any to mypy and an Any base 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 an isinstance assertion in the tests instead.

  • Both classes use __slots__, because the ABCs are built for it: JoinablePath, ReadablePath, WritablePath and abc.ABC all declare __slots__ = (), so omitting it would put a __dict__ back on every instance and waste that. It also keeps glob/walk cheap, which mint one path and one info per entry (measured ~15% less memory over 400 entries). The cost is that functools.cached_property is unavailable, which is why the info cache is hand-rolled.

  • iterdir() translates errors and fails eagerly. LittleFSError is not an OSError, so the ABC's except OSError guards in glob()/walk() never fired and (fs.root / "file.txt").glob("*") raised LFS_ERR_NOTDIR where pathlib yields nothing. iterdir() now raises NotADirectoryError / FileNotFoundError — matching what open(), mkdir() and remove() already do — and raises them at call time rather than on first iteration, because the globber builds a generator expression over iterdir() outside its own try block.

  • iterdir() uses scandir(), not listdir(), and primes each child's info with the type it already learned, saving a stat() per entry during glob/walk. The listing is materialised before the first yield so the directory handle is closed and callers can mutate the tree while iterating.

  • info caches, exists() doesn't. The PathInfo protocol permits cached results and the ABC's glob/walk rely on it, so LittleFSPathInfo caches one stat(). The exists()/is_file()/is_dir() methods on the path always do a fresh lookup, as pathlib.Path does.

  • Missing/existing paths are handled twice. LittleFS.stat() raises a raw LittleFSError(-2) while mkdir()/remove()/open() translate to builtins, so the code catches both FileNotFoundError/FileExistsError and LittleFSError with the matching code. If you'd rather translate consistently in the LittleFS methods themselves, that would let this be simplified.

  • rmdir() does not verify the target is a directory, because LittleFS.rmdir is an alias of remove and doesn't either. It therefore deletes a file, unlike pathlib.Path.rmdir. Kept consistent with the sibling API and documented; happy to add a check instead.

  • No match(). The ABCs provide full_match() (whole-path matching). pathlib's right-anchored match() 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() is False and readlink()/symlink_to() raise NotImplementedError. No mtimes either, so touch() only creates missing files and never updates an existing one.

Incidental changes

  • LittleFS.open()'s encoding/errors/newline annotations changed from str to Optional[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_imports for pathlib_abc (it ships no py.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) and codespell clean; mypy src/littlefs/path.py clean.
  • Docs build with no new Sphinx warnings (17 before, 17 after); doc8 unchanged.
  • Beyond unit assertions, test_end_to_end_roundtrip drives a real filesystem: builds a tree, verifies it through the low-level fs.listdir(), globs and reads it back, renames and unlinks, then tears the whole tree down through the path API.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant