How to Bump Version in pyproject.toml Using Regex in Python
Updates the version field in a pyproject.toml file using a regex substitution with the Python standard library.
Python code
26 linesimport re
from pathlib import Path
def bump_version(pyproject_path: str, new_version: str) -> None:
"""Update version in pyproject.toml using regex."""
path = Path(pyproject_path)
content = path.read_text()
# Match version = "x.y.z" (simple or PEP 440 with pre-release)
pattern = r'^version\s*=\s*"([^"]+)"'
new_content = re.sub(pattern, f'version = "{new_version}"', content, count=1, flags=re.MULTILINE)
path.write_text(new_content)
if __name__ == "__main__":
# Create test file
test_file = Path("pyproject_test.toml")
test_file.write_text('''[tool.poetry]
name = "demo"
version = "1.2.3"
description = "Test project"
''')
bump_version("pyproject_test.toml", "2.0.0")
print(test_file.read_text())
test_file.unlink()
Output
[tool.poetry]
name = "demo"
version = "2.0.0"
description = "Test project"
How it works
The regex pattern ^version\s*=\s*"([^"]+)" matches lines starting with version, allowing flexible whitespace and capturing the version inside quotes. Using re.MULTILINE makes ^ match at the start of each line. The count=1 ensures only the first occurrence is replaced, typically the correct field in pyproject.toml. After reading and modifying the content, path.write_text writes back the updated file.
Common mistakes
- Forgetting `flags=re.MULTILINE` so `^` only matches at the string start.
- Not using `count=1` if there are multiple `version` lines (e.g., in dependencies).
- Assuming the version is always simple `x.y.z` without pre-release suffixes.
- Writing to the same path without checking file existence or permissions.
Variations
- Use `re.sub(r'^(version\s*=\s*)"[^"]+"', r'\1"' + new_version + '"', content, flags=re.MULTILINE)` for a more precise replacement.
- Parse TOML with `tomllib` (Python 3.11+) to modify structured data instead of regex.
Real-world use cases
- Automating version increments in CI/CD pipelines before publishing a package.
- Updating the version in a monorepo's pyproject.toml as part of a release script.
- Synchronizing version numbers across multiple pyproject.toml files in a multi-package project.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.