Type-safe YAML configuration management for Python
Transform your YAML config files into strongly-typed Python dataclasses with full IDE autocomplete support
Stop wrestling with dictionaries and string keys. Heracless automatically converts your YAML configuration files into Python dataclasses with full type safety and IDE autocomplete support. Plus it's written in Rust for blazing-fast performance.
# WITHOUT Heracless - prone to typos, no autocomplete
config = yaml.load(open("config.yaml"))
db_host = config["database"]["host"] # Runtime errors waiting to happen
db_port = config["databse"]["port"] # Typo goes unnoticed!
# WITH Heracless - type-safe, autocomplete, catch errors at write-time
config = load_config()
db_host = config.database.host # Autocomplete works!
db_port = config.database.port # Typos caught by IDE/mypy- Automatic Type Generation - Generates
.pyistub files for full IDE support - Type Safety - Catch configuration errors at development time, not runtime
- Zero Boilerplate - No manual dataclass definitions needed
- IDE Autocomplete - Full IntelliSense/autocomplete for all config values
- Immutable by Default - Frozen dataclasses prevent accidental modifications
- Rust-Powered Performance - Native Rust backend for blazing-fast YAML parsing and stub generation
pip install heraclessgit clone https://github.com/felixscode/heracless.git
cd heracless
pip install -e .| Python Version | Status |
|---|---|
| 3.10 - 3.13 | Fully Supported |
| 3.9 and below | Not Supported |
Dependencies: PyYAML, black, art
Note: Prebuilt Rust wheels are available for Linux, macOS, and Windows. No Rust installation required!
Create a config.yaml file with your settings:
# config.yaml
database:
host: localhost
port: 5432
name: myapp_db
credentials:
username: admin
password: secret123 # don't use this in production
api:
base_url: https://api.example.com
timeout: 30
retries: 3
features:
enable_caching: true
max_cache_size: 1000Create a load_config.py file in your project:
# src/myproject/load_config.py
from pathlib import Path
from typing import TypeVar
from heracless import load_config as _load_config
# Point to your config file
CONFIG_YAML_PATH = Path(__file__).parent.parent / "config.yaml"
Config = TypeVar("Config")
def load_config(config_path: Path | str = CONFIG_YAML_PATH,
frozen: bool = True,
stub_dump: bool = True) -> Config:
"""Load configuration and generate type stubs."""
file_path = Path(__file__).resolve() if stub_dump else None
return _load_config(config_path, file_path, frozen=frozen)# src/myproject/main.py
from myproject.load_config import load_config
# Load config - first run generates load_config.pyi with types!
config = load_config()
# Access config with autocomplete and type checking
print(f"Connecting to {config.database.host}:{config.database.port}")
print(f"Database: {config.database.name}")
print(f"API URL: {config.api.base_url}")
print(f"Caching enabled: {config.features.enable_caching}")Output:
Connecting to localhost:5432
Database: myapp_db
API URL: https://api.example.com
Caching enabled: True
After the first run, Heracless automatically generates a load_config.pyi file:
# load_config.pyi (auto-generated)
from dataclasses import dataclass
from typing import TypeVar
@dataclass(frozen=True)
class Credentials:
username: str
password: str
@dataclass(frozen=True)
class Database:
host: str
port: int
name: str
credentials: Credentials
@dataclass(frozen=True)
class Api:
base_url: str
timeout: int
retries: int
@dataclass(frozen=True)
class Features:
enable_caching: bool
max_cache_size: int
@dataclass(frozen=True)
class Config:
database: Database
api: Api
features: FeaturesThis stub file enables full IDE autocomplete and type checking
from myproject.load_config import load_config
# Load with defaults (frozen, with stub generation)
config = load_config()
# Access nested values with autocomplete
db_url = f"{config.database.host}:{config.database.port}"# Load mutable config for testing or dynamic updates
config = load_config(frozen=False)
# Modify values (only works with frozen=False)
config.database.host = "192.168.1.100"from heracless.utils.helper import as_dict
config = load_config()
config_dict = as_dict(config)
# Now a regular Python dictionary
print(config_dict["database"]["host"]) # localhostfrom heracless.utils.helper import from_dict
config_dict = {
"database": {
"host": "localhost",
"port": 5432
},
"api": {
"base_url": "https://api.example.com",
"timeout": 30
}
}
config = from_dict(config_dict, frozen=True)
print(config.database.host) # localhost (with type checking!)from heracless.utils.helper import mutate_config
config = load_config()
# Create a new config with updated value (immutable pattern)
new_config = mutate_config(config, "database.host", "production-db.example.com")
print(config.database.host) # localhost (original unchanged)
print(new_config.database.host) # production-db.example.comHeracless includes a CLI tool for generating stub files and validating configs:
# Generate stub file from config
python -m heracless config.yaml --parse types.pyi
# Dry run (validate config without generating files)
python -m heracless config.yaml --dry
# Show help
python -m heracless --helpHere's a recommended project structure:
my_project/
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── main.py
│ └── config/
│ ├── __init__.py
│ ├── load_config.py # Your config loader
│ └── load_config.pyi # Auto-generated types
├── config/
│ ├── config.yaml # Main config
│ ├── config.dev.yaml # Development overrides
│ └── config.prod.yaml # Production overrides
├── tests/
│ └── test_config.py
├── pyproject.toml
└── README.md
Solutions:
- Ensure the
.pyifile exists next to yourload_config.py - Reload your IDE/editor window
- Check that your language server is running (VSCode: check Python extension)
- For PyCharm: File → Invalidate Caches → Restart
Solution: This is by design (frozen dataclass). To modify configs:
- Use
mutate_config()helper to create updated copies - Or load with
frozen=Falsefor mutable configs (not recommended)
Solution: Ensure your YAML is valid:
# Validate YAML syntax
python -c "import yaml; yaml.safe_load(open('config.yaml'))"Load a YAML configuration file and convert it to a typed dataclass.
Parameters:
config_path(Path | str): Path to the YAML configuration filefile_path(Path | str | None): Path where stub file should be generated (None to skip)frozen(bool): Whether the resulting dataclass should be immutable (default: True)
Returns: Config dataclass with attributes matching your YAML structure
Raises:
FileNotFoundError: If config file doesn't existyaml.YAMLError: If YAML file is malformed
Create a new config with an updated value (immutable pattern).
from heracless.utils.helper import mutate_config
config = load_config()
new_config = mutate_config(config, "database.port", 3306)Convert a Config dataclass to a nested dictionary.
from heracless.utils.helper import as_dict
config = load_config()
config_dict = as_dict(config) # Returns: dictCreate a Config dataclass from a dictionary.
from heracless.utils.helper import from_dict
config_dict = {"database": {"host": "localhost"}}
config = from_dict(config_dict, frozen=True)Contributions are welcome! Here's how you can help:
# Clone the repository
git clone https://github.com/felixscode/heracless.git
cd heracless
# Install with development dependencies
pip install -e .[dev]
# Run tests
pytest
# Run type checking
mypy heracless
# Run code formatting
black heracless tests# Run all tests
pytest
# Run with coverage
pytest --cov=heracless --cov-report=html
# Run specific test file
pytest tests/test_config.pyInstall development dependencies with:
pip install -e .[dev]This includes:
pytest- Testing frameworkpytest-cov- Coverage reportingmypy- Static type checkingtypes-PyYAML- Type stubs for PyYAML
To work on the documentation:
# Install documentation dependencies
pip install -e .[doc]
# Serve documentation locally
mkdocs serve
# Build documentation
mkdocs buildFound a bug or have a feature request? Open an issue on GitHub.
Please include:
- Heracless version (
pip show heracless) - Python version
- Operating system
- Minimal reproducible example
- Expected vs actual behavior
- Config variants - Support for environment-specific configs (dev/staging/prod)
- Environment variable interpolation -
${ENV_VAR}syntax in YAML
Heracless is released under the MIT License. See LICENSE file for details.
MIT License
Copyright (c) 2023 Felix Schelling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
TL;DR: You can freely use, modify, and distribute this software, even for commercial purposes.
- PyPI Package: pypi.org/project/heracless
- Documentation: heracless.io
- GitHub Repository: github.com/felixscode/heracless
- Issues & Support: GitHub Issues
Felix Schelling
- GitHub: @felixscode
- Website: felixschelling.de
If Heracless helps your project, consider giving it a star on GitHub!