How to Mock a pyenv Local Version File in Python

Read and write a mock .python-version file using the pathlib module and tempfile for isolated testing.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Python code

25 lines
Python 3.9+
import json
import tempfile
from pathlib import Path


def read_pyenv_local(directory: Path) -> str:
    """Read the .python-version file in the given directory."""
    version_file = directory / ".python-version"
    if not version_file.exists():
        return "no-version-file"
    return version_file.read_text().strip()


def write_pyenv_local(directory: Path, version: str) -> None:
    """Write a mock .python-version file."""
    (directory / ".python-version").write_text(version + "\n")


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as tmp:
        project_dir = Path(tmp) / "my_project"
        project_dir.mkdir()
        write_pyenv_local(project_dir, "3.11.5")
        result = read_pyenv_local(project_dir)
        print(json.dumps({"project": project_dir.name, "version": result}))

Output

stdout
{"project": "my_project", "version": "3.11.5"}

How it works

The script creates a temporary directory with tempfile.TemporaryDirectory, then writes a mock .python-version file using Path.write_text. The read_pyenv_local function checks if the file exists and returns its contents stripped of trailing whitespace. This mimics the pyenv version file behavior for testing or building tools that depend on it. Using tempfile ensures the test doesn't pollute the filesystem and cleans up automatically.

Common mistakes

  • Forgetting to strip newline characters from the read version string
  • Checking for the file before creating the directory structure
  • Not using a temporary directory, which leaves test artifacts behind

Variations

  1. Use `unittest.mock.patch` with `mock_open` to avoid real file I/O
  2. Parse the version file with `tomllib` if you need TOML support instead

Real-world use cases

  • Testing a project setup script that validates Python version constraints before installing dependencies.
  • Building a CI pipeline helper that reads the pinned version to choose the correct runner image.
  • Creating a local development bootstrapper that verifies the environment file matches the required runtime.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.