loadcfg Module

loadcfg: A configuration helper library.

This library provides functions to load configuration files in JSON, YAML, TOML, and INI formats into a configuration object that supports attribute (dot) access. It also supplies a base Template class to create configuration schemas, validate loaded configurations, and generate example configuration files.

class loadcfg.Config(data)[source]

Bases: dict

Configuration object that supports attribute access to dictionary keys.

This class recursively converts dictionaries into Config objects, allowing dot notation access to configuration values.

Example

config = Config({‘name’: ‘Alice’, ‘age’: 30}) print(config.name) # Output: Alice

validate(template)[source]

Validate the configuration against a given template.

This method delegates to the template’s class method.

Parameters:

template (Type[Template]) – The Template class to validate against.

Raises:

ConfigValidationError – If the configuration does not match the template.

exception loadcfg.ConfigValidationError(message)[source]

Bases: Exception

Exception raised for errors in configuration validation.

message

Explanation of the error.

Type:

str

class loadcfg.GeneratedConfig(content, fmt)[source]

Bases: object

Wrapper for generated configuration content that adds a .save() method.

content

The generated configuration string.

Type:

str

fmt

The format of the configuration (‘json’, ‘yaml’, ‘toml’, or ‘ini’).

Type:

str

save(filename=None)[source]

Save the generated configuration to a file.

If no filename is provided, a default filename of config.<fmt> is used.

Parameters:

filename (str, optional) – The file name to save the configuration. Defaults to None.

Returns:

The filename where the configuration was saved.

Return type:

str

loadcfg.LoadIni(file_path)[source]

Load an INI configuration file and return a Config object.

Parameters:

file_path (str) – Path to the INI file.

Returns:

The loaded configuration as a Config object.

Return type:

Config

Raises:
loadcfg.LoadJson(file_path)[source]

Load a JSON configuration file and return a Config object.

Parameters:

file_path (str) – Path to the JSON file.

Returns:

The loaded configuration as a Config object.

Return type:

Config

Raises:
loadcfg.LoadToml(file_path)[source]

Load a TOML configuration file and return a Config object.

Parameters:

file_path (str) – Path to the TOML file.

Returns:

The loaded configuration as a Config object.

Return type:

Config

Raises:
  • FileNotFoundError – If the file does not exist.

  • toml.TomlDecodeError – If the file is not valid TOML.

  • ValueError – If the TOML file does not contain a top-level table.

loadcfg.LoadYaml(file_path)[source]

Load a YAML configuration file and return a Config object.

Parameters:

file_path (str) – Path to the YAML file.

Returns:

The loaded configuration as a Config object.

Return type:

Config

Raises:
  • FileNotFoundError – If the file does not exist.

  • yaml.YAMLError – If the file is not valid YAML.

  • ValueError – If the YAML file does not contain a top-level dictionary.

class loadcfg.Template[source]

Bases: object

Base class for configuration templates.

Subclass this to define a configuration schema. Use type annotations to specify the expected fields and their types.

Example

class ProgramConfig(Template):

name: str age: int

# Validate a loaded config: config = LoadYaml(“config.yaml”) ProgramConfig.validate(config)

# Generate an example configuration (JSON format by default) and save it: example_config = ProgramConfig.generate(fmt=”json”) print(example_config) # Prints the configuration as a string. example_config.save(“test.json”) # Saves to test.json (or default “config.json”).

classmethod generate(fmt='json')[source]

Generate an example configuration based on the template.

The example is generated using default values for basic types. For instance, int becomes 0, str becomes “example”, and bool becomes False. For nested templates, the generation is done recursively.

Parameters:

fmt (str) – Format of the output. Supported values are “json”, “yaml” (or “yml”), “toml”, and “ini”. Defaults to “json”.

Returns:

An object containing the generated configuration and a .save() method.

Return type:

GeneratedConfig

Raises:

ValueError – If the specified format is unsupported.

classmethod validate(config)[source]

Validate that the given configuration matches the template.

This method checks that all required fields are present in the config and that the types of the provided values match the expected types. If a field’s expected type is a subclass of Template, the validation is performed recursively.

Parameters:

config (Config) – The configuration object to validate.

Raises:

ConfigValidationError – If a required field is missing or if a field has an incorrect type.