A library to auto-create and validate TOML configuration files from templates
Project description
TOML-Init
A lightweight Python library for auto-creating and validating TOML-based configuration files from one or more default templates.
For use where you use multiple relatively independent modules that need config values and you want a standardized way to handle, implement, and validate.
Defaults
| Variable | Value |
|---|---|
DEFAULT_CONFIG_FOLDER_PATH |
<Current Working Directory>/config |
DEFAULT_CONFIG_DEFAULT_FOLDER_PATH |
<Current Working Directory>/defaults |
DEFAULT_CONFIG_FILE |
"config.toml" |
Features
-
Automatic directory setup
- Ensures your primary
configs/directory and itsdefaults/subdirectory exist (creates them if missing).
- Ensures your primary
-
Defaults merging
- Scans all
*.tomlfiles underconfigs/defaults/. Each top-level TOML table is treated as a “block” of settings. - Merges multiple default files into a single master
config.toml, with conflict detection.
- Scans all
-
Schema-driven validation
-
Each setting may be declared in two ways:
- Simple:
KEY = <defaultValue> - Full:
KEY = { defaultValue = <...>, type = "<int|float|bool|str>", min = <...>, max = <...>, allowedValues = [...], validator = "<name>" }
- Simple:
-
Supports numeric range checks (
min/max), enumerations (allowedValues), and custom validation hooks.
-
-
Custom validators
- Implement by subclassing
Validatorand registering viaregister_validator("name", instance). - Allows arbitrary user‑defined checks (e.g. path existence, regex match).
- Implement by subclassing
-
Preserves user overrides
- If users manually edit
config.toml, extra keys remain intact. - Invalid values are reset to defaults with a logged warning.
- If users manually edit
-
CLI & programmatic API
- Installable console script:
toml-initfor quick command-line setup. ConfigManagerclass for embedding in Python code.
- Installable console script:
-
Dry‑run & logging
--dry-runto validate without writing changes.- Verbose mode with
--verbosefor debug logging.
Installation
pip install toml-init
Package Structure
toml_init
├── __init__.py
├── __main__.py
├── exceptions.py
├── validators.py
└── manager.py
Quickstart (Python)
from pathlib import Path
from toml_init import ConfigManager, register_validator, Validator
# Optional: register a custom validator
class PathExistsValidator(Validator):
def validate(self, value):
from pathlib import Path as P
if not (isinstance(value, str) and P(value).exists()):
raise InvalidConfigValueError(f"Path not found: {value}")
return value
register_validator("path_exists", PathExistsValidator())
# Initialize and validate
cm = ConfigManager(
base_path=Path("configs"),
defaults_path=Path("configs/defaults"),
master_filename="config.toml"
)
cm.initialize(dry_run=False)
# Access validated settings
settings = cm.get_block("QuickBooks.Invoices.Saver")
print(settings["WINDOW_LOAD_DELAY"]) # e.g. 0.5
Quickstart (CLI)
# Create or validate configs in ./configs (defaults in ./configs/defaults)
toml-init
# Verbose & dry-run (no file writes)
toml-init --verbose --dry-run
# Custom paths
toml-init --base /etc/myapp/configs \
--defaults /etc/myapp/configs/defaults \
--master settings.toml
Example Project
A working sample lives under example_project/. Run python run_demo.py inside
that directory to generate config.toml using the defaults in
configs/defaults/example_defaults.toml.
Default File Format
Place your default templates in configs/defaults/. Each file may define multiple blocks (tables):
# defaults/app_defaults.toml
[__meta__]
name = "Config - QuickBooks Invoice Saver"
module_version = "0.1.0"
[QuickBooks.Invoices.Saver]
SHOW_TOASTS = true
WINDOW_LOAD_DELAY = { defaultValue = 0.5, type = "float", min = 0.0 }
NAVIGATION_DELAY = { defaultValue = 0.15, type = "float", min = 0.0 }
[MyApp.Logging]
LEVEL = { defaultValue = "INFO", type = "str", allowedValues = ["DEBUG","INFO","WARN","ERROR"] }
ENABLE_LOGS = { defaultValue = true, type = "bool" }
-
Block names = the table names (e.g.
QuickBooks.Invoices.Saver). -
Settings under each block may be:
- A primitive default:
KEY = 123(shorthand for a setting with onlydefaultValue). - A full schema object: specifying
type, optionalmin/max,allowedValues, andvalidator.
- A primitive default:
-
An optional
[__meta__]table may be present and is ignored by the library.
Supported Types
int,float,bool,str,list,dict,datetime,date,time- Numeric range checks with
min/max - Enumerations via
allowedValues - Custom hooks via
validator(must match a registeredValidator)
Exception Hierarchy
-
TomlInitError(base)MultipleConfigFilesErrorInvalidDefaultSchemaErrorInvalidConfigValueErrorBlockConflictError
Catch these to handle specific error cases gracefully.
Potential Future Features
| Feature | Description |
|---|---|
| Multiple config files | Will support having separate config files for organization purposes? |
| Comment injection | Allow comments to be specified in the defaults? |
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file toml_init-0.1.1.tar.gz.
File metadata
- Download URL: toml_init-0.1.1.tar.gz
- Upload date:
- Size: 14.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3d506dabff6def78a8bedf09b59558c8263532cfd3feab14f6905b3b17e158c6
|
|
| MD5 |
efef665061ef7ba8710608848c37fd08
|
|
| BLAKE2b-256 |
c901e51cb1cdf835e6c16d2671d29607325a0f7b3f4bb12946810b59e3459222
|
File details
Details for the file toml_init-0.1.1-py3-none-any.whl.
File metadata
- Download URL: toml_init-0.1.1-py3-none-any.whl
- Upload date:
- Size: 13.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a58ca11e813ed16434df92f13d48a77fc498263edd44eab986636bc5e0948e0d
|
|
| MD5 |
42cda26ffebd28b14249d4605b2ac999
|
|
| BLAKE2b-256 |
18af8dd396245afca41641be854fe542010be75b69f89637b1602bb88201ade2
|