Mock pip-compile to Resolve Requirements in Python

A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.

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

Python code

35 lines
Python 3.9+
import subprocess
import tempfile
from pathlib import Path


def compile_requirements_mock(requirements_in: str) -> str:
    """Mock pip-compile: resolve a simple requirements.in into a locked format."""
    lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
    result = []

    # Simulate resolving packages to pinned versions
    mock_versions = {
        "django": "4.2.7",
        "requests": "2.31.0",
        "flask": "3.0.0",
    }

    for line in lines:
        package = line.split("=")[0].split(">")[0].split("<")[0].strip()
        version = mock_versions.get(package, "1.0.0")
        result.append(f"{package}=={version}")

    return "\n".join(result)


if __name__ == "__main__":
    sample_input = """\
# Core dependencies
django>=4.0
requests==2.31.0
flask<4
"""
    locked = compile_requirements_mock(sample_input)
    print("Compiled requirements:")
    print(locked)

Output

stdout
Compiled requirements:
django==4.2.7
requests==2.31.0
flask==3.0.0

How it works

This function simulates the pip-tools pip-compile workflow by parsing a requirements.in string, stripping comments and blank lines, then mapping each package to a mock pinned version. It uses string splitting to extract package names from constraints like >=, ==, and <. The mock version dictionary hard-codes realistic versions for popular packages. Running as a script demonstrates the output format of a compiled/locked requirements file, typical of real pip-compile output.

Common mistakes

  • Not stripping whitespace before splitting versions, causing parsing errors
  • Assuming every line has a version constraint, breaking on plain package names
  • Forgetting to ignore comments and blank lines when parsing the input

Variations

  1. Parse the input with `regex` or `packaging.requirements` for robust handling
  2. Fetch real latest versions from PyPI using `requests` instead of a hard-coded dict

Real-world use cases

  • Testing CI pipelines without installing pip-tools by mocking the compile step
  • Generating example lock files for documentation or tutorials
  • Prototyping dependency resolution logic before integrating real pip-compile

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.