Trending

World technology news

→
Passing report locations directly to file APIs with Python 3.6 PathLike
Software Engineering · 2016
Software Engineering2016

Passing report locations directly to file APIs with Python 3.6 PathLike

A small report-location class demonstrates Python’s filesystem path protocol and the error produced by an invalid return type.

Archive retrospective · Topic year 2016

Developer's JournalPublished: Dec 5, 20266 min read
Reading progress0%
In this article
  1. A report location carries more than a filename
  2. The narrow contract of __fspath__
  3. Verify a valid path and an invalid return value
  4. Keep path construction and trust checks distinct
  5. Expose the path at the filesystem boundary
  6. Test filenames under each storage root
  7. Migrate call sites with observable checks

A report location carries more than a filename

An export service may keep its storage root, customer selection and report ID in separate fields. That structure is useful to the business logic and the logs. The operating system needs a path when the application finally opens the output file. If every caller joins the fields itself, path separators, unexpected extensions and working directories can affect each call differently. Python 3.6 introduced a filesystem path protocol through PEP 519. An object can implement one method to expose a path to compatible APIs. The small example represents a report location as a root and identifier and passes the object straight to open. Other supporting code can use the same path-producing method when it needs the filesystem representation.

The narrow contract of __fspath__

The __fspath__ method returns a filesystem path as str or bytes. os.fspath passes through inputs that already have one of those forms and uses the protocol for objects that implement it. The example stores the root as a pathlib.Path and builds the name after validating the report ID. It then delegates to os.fspath to turn the resulting Path into the required representation. Holding a Path internally and returning its string representation follows the protocol that consumers expect. An invalid type raises TypeError instead of silently converting a number or some other object into a possible filename. This behavior helps identify an erroneous provider at the boundary where it hands data to a filesystem API.

Service architectureConceptual sketch · summary of the article's technical flow

Verify a valid path and an invalid return value

I ran the example using Python 3.12.10 and a temporary directory. A ReportLocation instance for Job42 resolved to Job42.txt. Passing it directly to open created the file, and the second open call read the word approved. A separate class deliberately returned the number 42 from __fspath__. os.fspath raised TypeError before any file creation was attempted through that object. This exercises both the expected path and the type check in a current runtime. The historical Python 3.6 interpreter was not run. The example uses re.fullmatch for input validation, which is available in Python 3.6. A historical acceptance run should still verify file operations with the actual interpreter and filesystem.

from pathlib import Path
import os
import platform
import re
from tempfile import TemporaryDirectory

class ReportLocation:
    def __init__(self, root, report_id):
        if re.fullmatch(r"[A-Za-z0-9]+", report_id) is None:
            raise ValueError("report_id")
        self.root = Path(root)
        self.report_id = report_id

    def __fspath__(self):
        return os.fspath(self.root / (self.report_id + ".txt"))

class InvalidLocation:
    def __fspath__(self):
        return 42

with TemporaryDirectory() as folder:
    location = ReportLocation(folder, "Job42")
    with open(location, "w", encoding="utf-8") as stream:
        stream.write("approved")
    assert Path(os.fspath(location)).name == "Job42.txt"
    with open(location, encoding="utf-8") as stream:
        result = stream.read()
    assert result == "approved"
    try:
        os.fspath(InvalidLocation())
    except TypeError:
        print("invalid return: TypeError")
    else:
        raise AssertionError("Expected TypeError")
    print(Path(location).name, result)
    print("Python", platform.python_version())

Keep path construction and trust checks distinct

The identifier in the example is limited to ASCII letters and digits, excluding path separators, spaces and traversal components. A deployed service can need additional rules for platform-reserved names and the permissions of its storage root. Windows device names are one example. If an attacker can replace directories with symbolic links or platform-specific reparse points, validate the actual destination at the point of opening or use an operating-system facility that constrains resolution. Converting an object to a path string cannot establish that the destination is safe. Inspect the inputs, the filesystem permissions and the resolved destination when the deployment warrants those checks. The example writes only within a temporary directory created by the standard library.

Expose the path at the filesystem boundary

Application code can use the location object to retain information beyond a path, including a tenant identifier or retention policy. Convert it where a filesystem operation requires the path. If a third-party function explicitly accepts strings only, a call to os.fspath at that boundary makes the conversion visible. Sending the object across a JSON interface still requires a defined representation because the path protocol does not serialize other fields. A practical compatibility test calls the adapter and then opens the file using the same runtime and library combination as the deployment. The first step checks the object contract, while the second verifies that the library consumes the protocol correctly on the chosen environment.

Test filenames under each storage root

Using Path to join components delegates separator and root formatting to the platform’s path implementation. Application rules still determine whether ids can contain punctuation, where a relative path starts, and which directories a user can use. Moving a service across machines is easier when report IDs and extensions remain stable and each installation computes its own storage path. When file operations fail, record the operation and report ID. Include a full local directory only when the application’s logging policy permits it and the information helps diagnose the failure. This keeps the relationship between identifiers and real files inspectable without exposing extra deployment details by default.

Migrate call sites with observable checks

A team replacing scattered path joins can start by finding the file reads and writes that use them. Run the previous implementation and the adapter against separate temporary roots and compare filenames and contents. Include negative tests for an invalid return type, an unacceptable identifier and an inaccessible destination. The outcomes identify whether input validation, the protocol or the actual open operation rejected the call. The adapter then provides one place to update a naming rule rather than making the same edit across exporters. In this example, Job42.txt approved and invalid return: TypeError are the two expected results.

Further reading / Referencehttps://peps.python.org/pep-0519/ ↗
425 reads ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.