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.
Python code
35 linesimport 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
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
- Parse the input with `regex` or `packaging.requirements` for robust handling
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.