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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

26 lines
Python 3.9+
import 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

stdout
[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

  1. Use `re.sub(r'^(version\s*=\s*)"[^"]+"', r'\1"' + new_version + '"', content, flags=re.MULTILINE)` for a more precise replacement.
  2. 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

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.