TOML Sort
toml-sort is a Python library and command-line utility for sorting and formatting TOML files. It provides features like sorting tables and arrays of tables, preserving comments, and standardizing whitespace and indentation. The library is actively maintained, with frequent releases, and is currently at version 0.24.4.
Warnings
- breaking Version 0.24.0 dropped official support for Python 3.7 and 3.8. Users should upgrade to Python 3.9 or newer.
- breaking Version 0.24.0 removed support for `tomlkit` versions older than 0.13.2. Ensure `tomlkit` is updated.
- gotcha Sorting inline tables with keys containing trailing spaces could cause a `ValueError` in versions 0.24.0 and 0.24.1. This was a regression.
- gotcha By default, `toml-sort` only sorts non-inline tables and arrays of tables. To sort all keys, including scalars and non-table entries, use the `--all` CLI option or configure `sort_all = true` in `pyproject.toml`.
- gotcha Comment handling can be complex. While `toml-sort` strives to preserve comments, specific types of comments (header, footer, inline, block) can be selectively disabled via CLI switches, which will lead to their removal.
- gotcha `toml-sort` can be configured via `pyproject.toml` under the `[tool.toml_sort]` section. Command-line arguments will always take precedence over `pyproject.toml` settings in case of conflicts.
Install
-
pip install toml-sort
Imports
- sort_toml_string
from toml_sort.tomlsort_tool import sort_toml_string
- sort_toml_file
from toml_sort.tomlsort_tool import sort_toml_file
Quickstart
from toml_sort.tomlsort_tool import sort_toml_string unsorted_toml = ''' [database] ports = [8000, 8001, 8002] enabled = true [owner] name = "Tom" dob = 1979-05-27T07:32:00-08:00 ''' sorted_toml = sort_toml_string(unsorted_toml) print(sorted_toml)