### Example Project Structure Source: https://heracless.io/quick-start A recommended directory structure for a project using Heracless. It organizes configuration files, source code, and generated type stubs logically. ```tree 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 ``` -------------------------------- ### Install Heracless from Source Source: https://heracless.io/installation Install the latest development version of Heracless by cloning the repository and installing it in editable mode. This is useful for contributors or users who need the absolute newest features. ```bash git clone https://github.com/felixscode/heracless.git cd heracless pip install -e . ``` -------------------------------- ### Create Configuration File (YAML) Source: https://heracless.io/quick-start Defines the structure for application settings in a YAML format. This file serves as the primary source of configuration for the application. ```yaml # 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: 1000 ``` -------------------------------- ### Install Heracless via PyPI Source: https://heracless.io/installation The recommended method for installing Heracless is using pip, which automatically handles dependencies. This ensures you have a stable and tested version of the library. ```bash pip install heracless ``` -------------------------------- ### Development Installation of Heracless Source: https://heracless.io/installation Install Heracless with development dependencies, including tools for testing and type checking, by cloning the repository and using pip with the 'dev' extra. This is essential for developers contributing to the project. ```bash # Clone the repository git clone https://github.com/felixscode/heracless.git cd heracless # Install with development dependencies pip install -e .[dev] ``` -------------------------------- ### Set Up Config Loader (Python) Source: https://heracless.io/quick-start Creates a Python function to load the Heracless configuration. It handles loading from a specified path, optionally freezing the config, and generating type stubs for improved developer experience. ```python # 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) ``` -------------------------------- ### Verify Heracless Installation Source: https://heracless.io/installation Confirm that Heracless has been installed correctly by checking its version using Python's import mechanism or by running the command-line interface tool. ```bash python -c "import heracless; print(heracless.__version__)" ``` ```bash python -m heracless --help ``` -------------------------------- ### Use Configuration in Application (Python) Source: https://heracless.io/quick-start Demonstrates how to load and access configuration values within a Python application. The `load_config` function provides type-safe access to settings, enabling IDE autocompletion and type checking. ```python # 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}") ``` -------------------------------- ### Configure Stub File Generation in Python Source: https://heracless.io/troubleshooting Example of how the `load_config` function is configured to generate stub files (`.pyi`). It shows the `stub_dump` parameter and how `file_path` is determined based on it, ensuring type information is available for static analysis. ```python from pathlib import Path def load_config(..., stub_dump: bool = True) -> Config: file_path = Path(__file__).resolve() if stub_dump else None return _load_config(config_path, file_path, frozen=frozen) ``` -------------------------------- ### Verify Config File Existence (Shell) Source: https://heracless.io/troubleshooting A simple shell command to list the details of a specific configuration file. This helps verify if the file exists at the expected location, addressing `FileNotFoundError`. ```shell ls -la config.yaml ``` -------------------------------- ### Load Config with Mutability Enabled (Python) Source: https://heracless.io/troubleshooting Shows how to load a configuration object with mutability enabled by setting `frozen=False`. This is generally not recommended for production environments due to the loss of immutability guarantees. ```python config = load_config(frozen=False) config.database.host = "new-host" ``` -------------------------------- ### Check Mypy Version (Shell) Source: https://heracless.io/troubleshooting A shell command to display the installed version of the `mypy` static type checker. This is useful for verifying that the correct version is being used and for troubleshooting compatibility issues. ```shell mypy --version ``` -------------------------------- ### Heracless CLI Tool Usage Source: https://heracless.io/usage Provides examples of using the Heracless command-line interface (CLI) tool for generating stub files from configuration and performing dry runs for validation. ```bash # 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 --help ``` -------------------------------- ### Set Relative Path for Config File (Python) Source: https://heracless.io/troubleshooting Illustrates how to define a configuration file path relative to the current script's location using Python's `Path` object. This ensures the configuration file is found correctly regardless of the script's execution directory. ```python from pathlib import Path CONFIG_YAML_PATH = Path(__file__).parent / "config.yaml" ``` -------------------------------- ### Generated Type Stub (Python) Source: https://heracless.io/quick-start An auto-generated Python type stub file (`.pyi`) created by Heracless. This file provides type hints for the configuration, enabling static analysis tools and IDEs for autocompletion and type checking. ```python # load_config.pyi (auto-generated - do not edit manually!) 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: Features ``` -------------------------------- ### Mutate Immutable Config Object with Python Source: https://heracless.io/troubleshooting Demonstrates how to safely modify an immutable configuration object in Python using the recommended `mutate_config` helper function. This approach ensures immutability while allowing for controlled updates to configuration values. ```python from heracless.utils.helper import mutate_config config = load_config() new_config = mutate_config(config, "database.host", "new-host") ``` -------------------------------- ### Validate YAML Syntax with Python Source: https://heracless.io/troubleshooting Provides a Python command-line snippet to validate the syntax of a YAML configuration file. This is useful for catching common errors such as incorrect indentation, missing colons, or invalid characters. ```python python -c "import yaml; yaml.safe_load(open('config.yaml'))" ``` -------------------------------- ### Run Mypy Type Checker (Shell) Source: https://heracless.io/troubleshooting Command to execute the `mypy` static type checker on a Python project directory. This is used to ensure type safety and catch potential typos or attribute access errors. ```shell mypy --strict src/ ``` -------------------------------- ### Load Configuration with Defaults (Python) Source: https://heracless.io/usage Demonstrates loading configuration with default settings, which are frozen and include stub generation. Access nested values using attribute access. ```python 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}" ``` -------------------------------- ### Create Configuration from Dictionary (Python) Source: https://heracless.io/usage Demonstrates creating a Heracless configuration object from a Python dictionary using the `from_dict` helper function. Supports type checking and optional freezing of the resulting configuration. ```python from 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!) ``` -------------------------------- ### Load Mutable Configuration (Python) Source: https://heracless.io/usage Shows how to load a configuration that is not frozen, allowing for modifications. This is useful for testing or dynamic updates. ```python # 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" ``` -------------------------------- ### Python YAML Config Comparison: Dict vs. Heracless Source: https://heracless.io/index This snippet illustrates the difference between managing YAML configurations using raw dictionaries (prone to runtime errors and typos) and using Heracless (type-safe with IDE support). It highlights how Heracless catches errors at write-time. ```python # WITHOUT Heracless - prone to typos, no autocomplete import yaml # Assume config.yaml exists and is loaded # 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 # from myproject.load_config import load_config # config = load_config() # db_host = config.database.host # Autocomplete works! # db_port = config.database.port # Typos caught by IDE/mypy ``` -------------------------------- ### CLI Tool Usage Source: https://heracless.io/api-reference Provides instructions on how to use the Heracless command-line interface for parsing configuration files and validating them. ```APIDOC ## CLI Tool ### Description Use the Heracless CLI to parse configuration files, generate stub files, or validate configurations. ### Method Command Line Interface ### Endpoint `python -m heracless [OPTIONS]` ### Parameters #### Path Parameters * **CONFIG_PATH** (str) - Required - Path to the YAML config file #### Query Parameters None #### Request Body None ### Arguments & Options * **`--parse OUTPUT_PATH`**: Generate stub file at the specified `OUTPUT_PATH`. * **`--dry`**: Validate the configuration without generating any files. * **`--help`**: Show the help message and exit. ### Request Example ```bash python -m heracless config.yaml --parse config_stub.py python -m heracless config.yaml --dry ``` ### Response Output will be printed to the console or files will be generated based on the options provided. ``` -------------------------------- ### Python: Load YAML Config with Heracless Source: https://heracless.io/index Demonstrates how to load a YAML configuration file using Heracless. It shows the import statement and how to access configuration values through generated dataclass attributes, providing type safety and autocomplete. ```python from myproject.load_config import load_config config = load_config() print(f"Connecting to {config.database.host}:{config.database.port}") ``` -------------------------------- ### Heracless CLI Tool Usage Source: https://heracless.io/api-reference The Heracless command-line interface allows users to parse configuration files. It takes the path to a YAML config file as a required argument and supports options for generating stub files, performing dry runs for validation, and displaying help messages. ```bash python -m heracless CONFIG_PATH [OPTIONS] # Example with stub generation: python -m heracless path/to/config.yaml --parse path/to/stub.py # Example dry run: python -m heracless path/to/config.yaml --dry ``` -------------------------------- ### Helper Functions - from_dict Source: https://heracless.io/api-reference Creates a Config dataclass object from a given dictionary. It also allows controlling whether the resulting dataclass should be immutable. ```APIDOC ## `from_dict()` ### Description Create a Config dataclass from a dictionary. ### Method N/A (Python Function) ### Endpoint N/A (Python Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config_dict** (dict) - Required - Dictionary to convert * **frozen** (bool) - Optional - Whether to make the config immutable (default: `True`) ### Request Example ```python from heracless.utils.helper import from_dict config_data = { "database": { "port": 5432 } } new_config = from_dict(config_data, frozen=False) ``` ### Response #### Success Response * **Config dataclass** - Config dataclass created from the dictionary #### Response Example ```json { "database": { "port": 5432 } } ``` ``` -------------------------------- ### Convert Configuration to Dictionary (Python) Source: https://heracless.io/usage Utilizes the `as_dict` helper function to convert a Heracless configuration object into a standard Python dictionary. This allows for dictionary-style access to configuration values. ```python 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"]) ``` -------------------------------- ### Update Configuration Values Immutably (Python) Source: https://heracless.io/usage Illustrates updating configuration values using the `mutate_config` function, which returns a new configuration object with the specified changes, preserving the original configuration. ```python 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.com ``` -------------------------------- ### Type Checking with mypy (Python) Source: https://heracless.io/usage Shows how Heracless integrates with mypy for static type checking, catching potential attribute errors like typos before runtime. ```python from myproject.load_config import load_config config = load_config() # This will be caught by mypy: # error: "Config" has no attribute "databse" host = config.databse.host # Typo! # This works: host = config.database.host ``` -------------------------------- ### Create Config from Dictionary Source: https://heracless.io/api-reference Creates a Config dataclass object from a given dictionary. It allows specifying whether the resulting dataclass should be immutable. This is the inverse operation of `as_dict()`. ```python from heracless.utils.helper import from_dict config = from_dict( config_dict: dict, frozen: bool = True ) ``` -------------------------------- ### Core Functions - load_config Source: https://heracless.io/api-reference Loads a YAML configuration file and converts it into a typed dataclass. It supports specifying a file path for generating a stub file and controlling the immutability of the resulting dataclass. ```APIDOC ## `load_config()` ### Description Load a YAML configuration file and convert it to a typed dataclass. ### Method N/A (Python Function) ### Endpoint N/A (Python Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config_path** (Path | str) - Required - Path to the YAML configuration file * **file_path** (Path | str | None) - Optional - Path where stub file should be generated (`None` to skip) * **frozen** (bool) - Optional - Whether the resulting dataclass should be immutable (default: `True`) ### Request Example ```python from heracless import load_config config = load_config( config_path='path/to/your/config.yaml', file_path='path/to/your/stub.py', frozen=False ) ``` ### Response #### Success Response * **Config dataclass** - Dataclass with attributes matching your YAML structure #### Response Example ```json { "attribute1": "value1", "nested": { "attribute2": 123 } } ``` ### Errors * **FileNotFoundError** - If config file doesn't exist * **yaml.YAMLError** - If YAML file is malformed ``` -------------------------------- ### Helper Functions - as_dict Source: https://heracless.io/api-reference Converts a Config dataclass object into a nested dictionary representation. This is useful for serializing configuration data. ```APIDOC ## `as_dict()` ### Description Convert a Config dataclass to a nested dictionary. ### Method N/A (Python Function) ### Endpoint N/A (Python Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (Config) - Required - Config object to convert ### Request Example ```python from heracless.utils.helper import as_dict config_dict = as_dict(my_config_object) ``` ### Response #### Success Response * **Dictionary** - Dictionary representation of the config object #### Response Example ```json { "database": { "port": 5432 } } ``` ``` -------------------------------- ### Mutate Configuration Object Source: https://heracless.io/api-reference Creates a new configuration object with an updated value using an immutable pattern. It takes the original config, a dot-separated path to the value to change, and the new value. The function returns a new config object, leaving the original untouched. ```python from heracless.utils.helper import mutate_config new_config = mutate_config( config: Config, name: str, value: Any ) ``` -------------------------------- ### Load Configuration from YAML Source: https://heracless.io/api-reference Loads a YAML configuration file and converts it into a typed dataclass. It supports specifying an output path for a stub file and controlling whether the resulting dataclass is immutable. This function can raise FileNotFoundError if the config file does not exist or yaml.YAMLError if the YAML is malformed. ```python from heracless import load_config config = load_config( config_path: Path | str, file_path: Path | str | None = None, frozen: bool = True ) ``` -------------------------------- ### Helper Functions - mutate_config Source: https://heracless.io/api-reference Creates a new configuration object with an updated value using an immutable pattern. It allows for updating nested values specified by a dot-separated path. ```APIDOC ## `mutate_config()` ### Description Create a new config with an updated value (immutable pattern). ### Method N/A (Python Function) ### Endpoint N/A (Python Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (Config) - Required - Original config object * **name** (str) - Required - Dot-separated path to the value (e.g., `"database.port"`) * **value** (Any) - Required - New value to set ### Request Example ```python from heracless.utils.helper import mutate_config new_config = mutate_config(original_config, "database.port", 5433) ``` ### Response #### Success Response * **New config object** - Config object with the updated value #### Response Example ```json { "database": { "port": 5433 } } ``` ``` -------------------------------- ### Convert Config to Dictionary Source: https://heracless.io/api-reference Converts a Config dataclass object into a nested dictionary representation. This is useful for serialization or further processing of the configuration data. ```python from heracless.utils.helper import as_dict config_dict = as_dict(config: Config) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.