API Reference
This page provides auto-generated documentation from the ConfigGuard source code docstrings.
Main Class
- class configguard.ConfigGuard(schema: dict | str | Path, config_path: str | Path | None = None, encryption_key: bytes | None = None, autosave: bool = False)[source]
Bases:
MutableMapping
Main class for managing application configurations. Agnostic of storage format.
Handles configuration schema definition (including nested sections), validation, loading/saving via storage handlers, encryption, versioning, and basic migration. Access settings via attribute (config.setting or config.section.setting) or dictionary syntax (config[‘setting’] or config[‘section’][‘setting’]). Access schema details via config.sc_setting or config.sc_section.sc_setting.
- VERSION_KEY = '__version__'
- SECTION_TYPE_KEY = 'section'
- __init__(schema: dict | str | Path, config_path: str | Path | None = None, encryption_key: bytes | None = None, autosave: bool = False) None [source]
Initializes ConfigGuard.
- Parameters:
schema – The configuration schema definition for this instance. Can be a dictionary or a path to a schema file (JSON expected). Should contain a top-level ‘__version__’ key (e.g., “1.0.0”). Can contain nested sections defined with “type”: “section”.
config_path – Path to the configuration file for loading/saving values or full state.
encryption_key – Optional bytes key for encrypting/decrypting the config file via the handler.
autosave – If True, automatically save configuration values (mode=’values’) whenever a setting is changed (including nested settings). Defaults to False.
- Raises:
SchemaError – If the schema definition is invalid or contains an invalid version format.
EncryptionError – If encryption_key is provided but cryptography is not installed or the key is invalid.
HandlerError – If config_path is provided but no suitable handler is found.
- load(filepath: str | Path | None = None) None [source]
Loads configuration using the configured handler. Handles versioning, migration, and nesting.
- save(filepath: str | Path | None = None, mode: str = 'values') None [source]
Saves the configuration using the configured handler and specified mode. Handles nesting.
- Parameters:
filepath – Optional path to save to. Overrides the instance’s config_path.
mode – Specifies what to save (‘values’ or ‘full’).
- Raises:
HandlerError – If saving fails (no path, no handler, serialization, encryption).
EncryptionError – If encryption specifically fails.
ValueError – If an invalid mode is provided.
- get_instance_schema_definition() dict [source]
Returns the schema definition used by this ConfigGuard instance (excludes version key).
- get_config_dict() dict [source]
Returns the current configuration values as a potentially nested dictionary.
- export_schema_with_values() dict [source]
Exports the current state (instance schema + values, including nested structures) for external use (e.g., UI).
- Returns:
A dictionary containing ‘version’, ‘schema’, and ‘settings’. The ‘settings’ dict maps names to {‘schema’: …, ‘value’: …}, where ‘value’ can be a nested dictionary for sections.
- import_config(data: Mapping, ignore_unknown: bool = True) None [source]
Imports configuration values from a potentially nested dictionary, validating against the instance schema.
- Parameters:
data – A dictionary (potentially nested) of {setting_name: value} or {section_name: {sub_setting: value}}.
ignore_unknown – If True (default), ignores keys/sections in data not present in the instance schema. If False, raises SettingNotFoundError for unknown keys/sections.
- __getattr__(name: str) Any [source]
Allows accessing settings/sections like attributes (e.g., config.port, config.section).
- __setattr__(name: str, value: Any) None [source]
Allows setting top-level settings like attributes (e.g., config.port = 8080).
- __getitem__(key: str) Any [source]
Allows accessing settings/sections like dictionary items (e.g., config[‘port’], config[‘section’]).
- __setitem__(key: str, value: Any) None [source]
Allows setting top-level settings like dictionary items (e.g., config[‘port’] = 8080).
Schema & Setting Classes
- class configguard.SettingSchema(name: str, definition: dict)[source]
Bases:
object
Represents the schema definition for a single configuration setting.
- __init__(name: str, definition: dict)[source]
Initializes the SettingSchema.
- Parameters:
name – The name of the setting.
definition – A dictionary defining the schema for this setting. Expected keys: ‘type’, ‘help’. Optional keys: ‘default’, ‘nullable’, ‘min_val’, ‘max_val’, ‘options’.
- validate(value: Any)[source]
Validates a value against the schema definition.
- Parameters:
value – The value to validate.
- Raises:
ValidationError – If the value is invalid according to the schema.
- class configguard.ConfigSetting(schema: SettingSchema, parent: ConfigGuard | ConfigSection | None = None)[source]
Bases:
object
Represents a single configuration setting, holding its schema, current value, and parent reference.
- __init__(schema: SettingSchema, parent: ConfigGuard | ConfigSection | None = None)[source]
Initializes a ConfigSetting.
- Parameters:
schema – The SettingSchema defining this setting.
parent – A reference to the containing ConfigGuard or ConfigSection instance, used primarily for triggering autosave. Defaults to None.
- property schema: SettingSchema
The schema definition for this setting.
Exceptions
- exception configguard.exceptions.ConfigMasterError[source]
Bases:
Exception
Base exception for all ConfigGuard errors.
- exception configguard.exceptions.SchemaError[source]
Bases:
ConfigMasterError
Error related to schema definition or validation.
- exception configguard.exceptions.ValidationError[source]
Bases:
ConfigMasterError
Error raised when a value fails validation against the schema.
- exception configguard.exceptions.HandlerError[source]
Bases:
ConfigMasterError
Error related to loading or saving configuration using a handler.
- exception configguard.exceptions.EncryptionError[source]
Bases:
ConfigMasterError
Error related to encryption or decryption.
- exception configguard.exceptions.SettingNotFoundError[source]
Bases:
ConfigMasterError
,KeyError
Error raised when trying to access a non-existent setting.
Handlers (Base Class)
- class configguard.handlers.StorageHandler(fernet: Any | None = None)[source]
Bases:
ABC
Abstract base class for all configuration storage handlers in ConfigGuard.
Concrete handlers must implement the load and save methods to interact with specific storage formats (e.g., JSON, YAML, TOML, Database). They should also handle encryption and decryption internally if a Fernet instance is provided during initialization.
- __init__(fernet: Any | None = None) None [source]
Initializes the storage handler.
- Parameters:
fernet – An optional initialized Fernet instance from the ‘cryptography’ library. If provided, the handler MUST use it to encrypt data before saving and decrypt data after loading from the physical storage. If None, data is saved/loaded in plain text.
- abstract load(filepath: Path) LoadResult [source]
Load configuration data from the specified file path.
Implementations must handle reading the file format correctly. If the handler was initialized with a Fernet instance (self._fernet), this method MUST first read the raw bytes, then attempt decryption using self._decrypt, and finally parse the decrypted data according to the storage format.
- Parameters:
filepath – The absolute or relative Path object pointing to the configuration file.
- Returns:
- ‘version’: The version string found in the file if the file represents
a ‘full’ save state, otherwise None.
- ’schema’: The schema dictionary found in the file if the file represents
a ‘full’ save state, otherwise None.
- ’values’: A dictionary containing the loaded configuration values
({setting_name: value}). This key MUST always be present, returning an empty dict if the file is empty or only contains metadata in ‘full’ mode.
- Return type:
A LoadResult dictionary containing
- Raises:
FileNotFoundError – If the file specified by filepath does not exist.
HandlerError – If loading, parsing, or data structure validation fails for reasons specific to the handler or format.
EncryptionError – If decryption fails (only applicable if initialized with Fernet).
- abstract save(filepath: Path, data: dict, mode: str = 'values') None [source]
Save configuration data to the specified file path.
Implementations must handle serializing the data according to the storage format. If the handler was initialized with a Fernet instance (self._fernet), this method MUST first serialize the appropriate data to bytes, then encrypt these bytes using self._encrypt, and finally write the encrypted bytes to the file.
- Parameters:
filepath – The absolute or relative Path object pointing to the target file. The handler should ensure parent directories exist.
data – A dictionary containing the full data payload from ConfigGuard. Expected keys are ‘instance_version’, ‘schema_definition’, ‘config_values’. The handler will use parts of this payload based on the mode.
mode – Specifies what to save. Accepts ‘values’ or ‘full’. If ‘values’ (default), saves only the current configuration key-value pairs. The file structure depends on the handler (e.g., simple JSON dict). If ‘full’, saves the instance version, schema definition, and values. The file structure also depends on the handler but typically includes distinct sections or keys for version, schema, and values.
- Raises:
HandlerError – If saving, serialization, or file writing fails for reasons specific to the handler or format.
EncryptionError – If encryption fails (only applicable if initialized with Fernet).
ValueError – If an unsupported mode is provided.
Note
Specific handler implementations (like JsonHandler
) are typically used internally via the get_handler
factory and the ConfigGuard
class based on file extensions. Their direct use is less common.
Utilities
- configguard.generate_encryption_key() bytes [source]
Generates a new Fernet key suitable for ConfigGuard encryption.
Requires the ‘cryptography’ library to be installed.
- Returns:
A URL-safe base64-encoded 32-byte key as bytes.
- Raises:
ImportError – If the ‘cryptography’ library is not installed.