How to Mock Poetry pyproject.toml Dependencies Sections in Python
Parse and extract dependency lists from Poetry-style pyproject.toml text using Python's standard library.
Python code
59 linesfrom pathlib import Path
import re
def parse_pyproject_dependencies(text):
"""Extract dependencies from a pyproject.toml style text."""
lines = text.splitlines()
sections = {
"dependencies": [],
"dev": [],
"optional": [],
}
current_section = None
patterns = {
"dependencies": r"^dependencies\s*=\s*\[",
"dev": r"^dev\s*=\s*\[",
"optional": r"^optional-dependencies\s*=",
}
for idx, line in enumerate(lines):
stripped = line.strip()
for section, pattern in patterns.items():
if re.match(pattern, line.strip()):
current_section = section
break
if current_section and stripped.startswith('"') and stripped.endswith('",'):
dependency = stripped.strip('",')
sections[current_section].append(dependency)
if current_section and stripped == "]":
current_section = None
return sections
if __name__ == "__main__":
sample_pyproject = '''
[tool.poetry]
name = "demo"
version = "0.1.0"
[tool.poetry.dependencies]
python = "^3.9"
requests = "^2.31.0"
flask = "^3.0.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.0"
black = "^23.9.0"
[tool.poetry.extras]
speed = ["uvloop"]
'''
result = parse_pyproject_dependencies(sample_pyproject)
for section, deps in result.items():
print(f"{section}: {deps}")
Output
dependencies: ['python', 'requests', 'flask']
dev: ['pytest', 'black']
optional: ['uvloop']
How it works
This parser reads a pyproject.toml string line-by-line, tracking the current TOML section with regex patterns for dependencies, dev, and optional-dependencies. It extracts lines that look like quoted strings inside dependency arrays, stripping quotes and commas. The parser resets the current section when it sees a closing bracket. This approach works for mocking or inspecting dependency structures without needing a TOML library, handy for quick checks, scripts, or test doubles.
Common mistakes
- Not handling the closing bracket `]` correctly, which causes dependencies from later sections to leak into the previous section.
- Assuming all dependency lines start with quotes — Poetry can use multiline arrays or unquoted package specs.
- Forgetting to reset `current_section` when encountering a new `[tool.poetry...]` header, mixing groups incorrectly.
Variations
- Use `tomllib` (Python 3.11+) to parse the file properly and access nested TOML tables.
- Extend patterns to capture dependencies from `tool.poetry.group.*.dependencies` with multiple group names.
Real-world use cases
- Emulating dependency extraction when testing a package manager CLI without installing Poetry.
- Scanning a monorepo for Python dependency declarations during license or security audits.
- Generating a quick inventory of required vs optional packages from a config file inside a CI script.
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.