Skip to main content

Python project helpers

Format-preserving TOML edits, project and package discovery, and version reading, writing, and bumping.

Utilities shared by Python project tooling (nbdev, fastship, and friends): lightweight format-preserving TOML edits, walking up to project markers and locating package directories, and reading, writing, and bumping X.Y.Z / X.Y.Z.postN versions.

from fastcore.test import *
from tempfile import TemporaryDirectory

Format-preserving TOML editing


source

toml_section_bounds

def toml_section_bounds(
    lines:list[str], # Lines of a TOML file (without trailing newlines)
    section:str, # Dotted section header name without brackets, e.g. `'project.urls'`
)->tuple[int | None, int | None]: # `(start_idx, end_idx)` or `(None, None)` when absent

Find the header index and exclusive end index of [section] in lines


source

fmt_toml_val

def fmt_toml_val(
    v, # Scalar or sequence of strings to format
)->str:

Format a simple Python scalar or string list as a TOML value literal

fmt_toml_val formats simple inline literals and toml_section_bounds locates [section] line ranges without re-serializing the file:

test_eq([fmt_toml_val(True), fmt_toml_val(['a', 'b']), fmt_toml_val('hi')], ['true', '["a", "b"]', '"hi"'])
test_eq(toml_section_bounds(['[a]', 'x = 1', '', '[b]', 'y = 2'], 'a'), (0, 3))
test_eq(toml_section_bounds(['[a]', 'x = 1'], 'missing'), (None, None))

source

replace_toml_section_key

def replace_toml_section_key(
    p:str | pathlib.Path, # TOML file to update in place
    section:str, # Section header name without brackets
    key:str, # Key name to replace inside `[section]`
    val:str, # New string value
):

Replace key = ... inside [section] of p, preserving surrounding formatting

replace_toml_section_key rewrites a single string key in place and raises ValueError if missing:

_td = TemporaryDirectory()
_toml = Path(_td.name)/'pyproject.toml'
_toml.write_text('[project]\nname = "demo"\nversion = "0.1.0"\n\n[project.urls]\nRepository = "https://github.com/org/demo"\n\n[project.scripts]\na = "b:c"\n')
replace_toml_section_key(_toml, 'project', 'version', '0.2.0')
assert 'version = "0.2.0"' in _toml.read_text()
with expect_fail(ValueError): replace_toml_section_key(_toml, 'project', 'missing', '1')

source

ensure_toml_section

def ensure_toml_section(
    p:str | pathlib.Path, # TOML file to update in place
    section:str, # Section header name without brackets
    items:dict, # Key/value pairs to ensure exist in `[section]`
    replace:bool=False, # Overwrite existing matching keys (case-insensitive)?
):

Ensure [section] in p contains items, preserving existing keys and blank-line spacing

ensure_toml_section inserts missing keys before any trailing blank line, matches existing keys case-insensitively, and appends missing sections:

ensure_toml_section(_toml, 'project.urls', {'repository': 'https://other/x', 'Documentation': 'https://org.github.io/demo/'})
ensure_toml_section(_toml, 'tool.demo', {'flag': True, 'items': ['a', 'b']})
test_eq(_toml.read_text(), '[project]\nname = "demo"\nversion = "0.2.0"\n\n[project.urls]\nRepository = "https://github.com/org/demo"\nDocumentation = "https://org.github.io/demo/"\n\n[project.scripts]\na = "b:c"\n\n[tool.demo]\nflag = true\nitems = ["a", "b"]\n')
_td.cleanup()

Project and package discovery


source

is_uv_workspace

def is_uv_workspace(
    data:dict
)->bool:

True when parsed pyproject.toml dict data defines [tool.uv.workspace]


source

find_pyproject

def find_pyproject(
    start:str | pathlib.Path | None=None, # Starting directory or file (defaults to current working directory)
)->pathlib.Path:

Find the nearest pyproject.toml in start or its parent directories


source

find_marker

def find_marker(
    start:str | pathlib.Path | None, # Starting directory or file (defaults to current working directory)
    *fnames:str, # Marker filenames to look for in priority order at each directory level
)->pathlib.Path:

Find the nearest of fnames in start or its parent directories

find_marker and find_pyproject walk parent directories to locate project files, and is_uv_workspace detects uv workspace roots:

_ws_td = TemporaryDirectory()
_ws = Path(_ws_td.name)
(_ws/'pyproject.toml').write_text('[tool.uv.workspace]\nmembers = ["*"]\n')
_proj = _ws/'my-pkg'
(_proj/'python'/'my_pkg').mkdir(parents=True)
(_proj/'python'/'my_pkg'/'__init__.py').write_text('')
(_proj/'pyproject.toml').write_text('[project]\nname = "my-pkg"\n[tool.maturin]\npython-source = "python"\n')
test_eq(find_pyproject(_proj/'python'), (_proj/'pyproject.toml').resolve())
assert is_uv_workspace((_ws/'pyproject.toml').read_toml())

source

project_root

def project_root(
    path:str | pathlib.Path | None=None, # Starting path (defaults to current working directory)
)->tuple[pathlib.Path, dict, pathlib.Path | None]: # `(root, data, pyproject_path)`

Nearest non-workspace project (root, data, pyproject_path), falling back to (resolved_path, {}, None)

project_root skips uv workspace roots so member directories without a pyproject.toml (such as pure Rust crates) resolve cleanly to themselves:

_root,_data,_pp = project_root(_proj/'python')
test_eq((_root, _pp), (_proj.resolve(), (_proj/'pyproject.toml').resolve()))
_crate = _ws/'pure-crate'
_crate.mkdir()
test_eq(project_root(_crate), (_crate.resolve(), {}, None))

source

norm_mod

def norm_mod(
    name:str
)->str:

Normalize a project name to a Python import/package name

norm_mod normalizes a distribution name to a Python module identifier:

test_eq(norm_mod('my-pkg'), 'my_pkg')

source

find_pkg_path

def find_pkg_path(
    root:str | pathlib.Path, # Project root directory
    data:dict=None, # Parsed `pyproject.toml` dict (read from `root/pyproject.toml` if None)
    pkg:str=None, # Explicit package directory name override
)->pathlib.Path:

Locate the Python package directory under root from pyproject.toml config or standard layouts

find_pkg_path checks [tool.nbdev].lib_path, maturin/setuptools source roots, explicit pkg overrides, normalized [project].name, and standard layouts:

test_eq(find_pkg_path(_root, _data), _root/'python'/'my_pkg')
test_eq(norm_mod('my-pkg'), 'my_pkg')
with expect_fail(FileNotFoundError): find_pkg_path(_crate, {})
_ws_td.cleanup()

Version reading, writing, and bumping


source

read_version

def read_version(
    path:str | pathlib.Path, # Package directory or `__init__.py` file
)->str | None:

Read literal __version__ from path (or path/__init__.py), returning None if absent

read_version extracts a literal __version__ string from a package directory or .py file, returning None when missing:

test_is(read_version(Path('nonexistent_pkg')), None)

source

set_version

def set_version(
    path:str | pathlib.Path, # Package directory or `__init__.py` file
    version:str, # New version string
)->bool: # True if file was created or updated

Set literal __version__ in path (or path/__init__.py), inserting after shebang/coding/docstring when absent

read_version and set_version accept either a package directory or a .py file; set_version updates an existing __version__ in place without adding extra blank lines, or inserts it after any module docstring:

with TemporaryDirectory() as td:
    pkg = Path(td)/'demo'
    init = pkg/'__init__.py'
    init.mk_write('"Demo pkg."\n\nimport os\n')
    test_is(read_version(pkg), None)
    assert set_version(pkg, '0.1.0')
    test_eq(read_version(pkg), '0.1.0')
    test_eq(init.read_text(), '"Demo pkg."\n__version__ = "0.1.0"\n\nimport os\n')
    assert not set_version(init, '0.1.0') and set_version(init, '0.1.1')
    test_eq(init.read_text(), '"Demo pkg."\n__version__ = "0.1.1"\n\nimport os\n')

source

bump_version

def bump_version(
    v:str, # Current version in `X.Y.Z` or `X.Y.Z.postN` format
    part:int=None, # Component to bump (`0`=major, `1`=minor, `2`=patch); default bumps `.postN` if present else patch
    unbump:bool=False, # Decrement instead of incrementing (clamped at 0)?
)->str:

Bump .postN by default when present, else semver part (0=major, 1=minor, 2=patch)

bump_version accepts strict X.Y.Z and X.Y.Z.postN versions, defaulting to .postN when present or patch otherwise:

test_eq([bump_version('1.2.3'), bump_version('1.2.3', 1), bump_version('1.2.3', 0)], ['1.2.4', '1.3.0', '2.0.0'])
test_eq(bump_version('0.0.0', unbump=True), '0.0.0')
test_eq([bump_version('2026.10.28.post0'), bump_version('2026.10.28.post2', unbump=True), bump_version('2026.10.28.post2', 2)],
    ['2026.10.28.post1', '2026.10.28.post1', '2026.10.29'])
with expect_fail(ValueError): bump_version('9.7.1.2')
with expect_fail(ValueError): bump_version('1.2.3', 3)