Core API#
The core API is centered on Confease, a configuration container that stores Confitem values with an origin and resolves conflicts through configurable precedence.
This reference is generated from the source docstrings using Sphinx autodoc.
See Configuration Model for manual editing, template defaults, reset
behavior, and migration from the removed editing user_only argument.
Origins#
- confease.CLI#
Origin name for values loaded from command-line arguments.
- confease.ENV#
Origin name for values loaded from environment variables.
- confease.SYS#
Origin name for values loaded from configuration files outside the current user’s home directory.
- confease.USR#
Origin name for values loaded from user configuration files or assigned through
Confease.set().
- confease.DEF#
Origin name for defaults supplied through
itemsor configured template values.
- confease.ORIGINS#
Ordered list of all supported origin names.
Confease#
- class confease.Confease(path=None, reload=False, parser=<class 'confease.parsers.Yaml'>, template=None, preference=('cli', 'env', 'system', 'user', 'default'), backup=False, items=None, *, autoload=True)#
Configuration container with defaults, persistence, and precedence.
Confeasekeeps one effective value per key. Values can come from defaults, files, environment variables, or command-line namespaces, and the configuredpreferencedecides which origin wins when multiple sources define the same key.Nested mappings support arbitrary depth and are flattened into dotted
Confitemleaves internally, with placeholders for empty mappings until descendants populate them. Mapping/non-mapping structural changes are rejected, while ordinary leaf type changes remain valid. Parsers encode hierarchy for their format and return canonical nested mappings on load. Dots are reserved path separators; lists remain whole values.- Parameters:
path (str | Path | None)
reload (bool)
parser (type[Parser] | None)
template (str | Path | None)
backup (bool)
items (dict[str, Any] | None)
autoload (bool)
- property preference#
Return source origins ordered from highest to lowest priority.
- load(path=None)#
Load configuration values from a file as user-origin entries.
Validate all content and keys before replacing in-memory entries. Failed loads preserve the previous entries; defaults supply keys not defined by the file. Successful loading, including from an alternate path, satisfies deferred initialization. With
reload=False, later ordinary access keeps those entries rather than loading the destination.- Parameters:
path (
str|Path|None) – Optional file path to load instead of the instance path.- Raises:
FileNotFoundError – If no path is available or the target file does not exist.
ValueError – If the parser rejects the file shape or keys collide.
- save(user_only=True, *, backup=None)#
Persist configuration to the instance path.
- Parameters:
user_only (
bool) – When true, write onlyUSRentries. When false, write all effective entries, including defaults and overrides from other origins.backup (
bool|None) –Noneinherits the instance policy; a boolean overrides it for this save only. After candidate validation, snapshot the previous bytes before replacement. Backup failure aborts saving.
Notes
A deferred instance initializes from its existing destination before saving, so unaccessed file values are retained. Initialization errors abort saving without changing the file or publishing partial entries. Runtime-only configurations created without
pathare a no-op when saved. Existing YAML, TOML, INI-family, and XML comments are preserved using the latest destination document. Selected in-memory values are authoritative; external values are not merged. Invalid destinations or unrepresentable values raise without replacing the file. Complete candidates are validated before replacement.
- reset(*, backup=None)#
Restore
itemsdefaults in memory, or copy the template to disk.With a template, explicitly overwrite the configured path with exact template bytes and reload them as user-origin values. Validation or copy failures leave the previous file and in-memory entries unchanged. Without a template, reset only memory and do not write the file. Reset bypasses deferred destination loading, including for malformed files.
- Parameters:
backup (
bool|None) – Override the instance backup policy for template restoration.Noneinherits it. Memory-only reset never creates a backup.- Raises:
FileNotFoundError – If template restoration lacks a target path or the template is missing.
ValueError – If the template has invalid shape or keys.
OSError – If copying or replacing the target fails.
- restore(path=None, *, backup=None)#
Restore exact backup bytes while retaining existing defaults.
- Parameters:
path (
str|Path|None) – Explicit source file, irrespective of filename or directory. When omitted, select the latest matching sibling backup by its embedded timestamp and collision sequence, not modification time.backup (
bool|None) – Override the instance backup policy for this operation.Noneinherits it. Select and validate the source before backing up the destination so a subsequent restore can undo this one. The source backup is retained.
- Raises:
FileNotFoundError – If no destination, source, or matching backup exists.
ValueError – If source structure or keys conflict with retained defaults.
OSError – If copying, backing up, or replacing the destination fails.
Notes
Validation uses the active parser. Malformed or missing destinations can be recovered; failures preserve the destination and live entries. Defaults, template, configured path, and instance policy are unchanged. Construct with
autoload=Falseto recover a malformed destination using a fresh instance without parsing it during construction.
- get(key, default=None, cast=None)#
Return a value or recursive section snapshot by path.
- Parameters:
key (
str) – Scalar key, dotted nested key, or section name.default – Value returned when neither a leaf nor a section exists.
cast – Optional callable used to coerce the returned value. Cast failures are reported and the original value is returned.
- Returns:
The stored value, a plain dictionary snapshot for section reads, or
defaultwhen the key is missing.
- get_item(key)#
Return the matching leaf item.
- Parameters:
key (
str) – Scalar or dotted key to look up.- Return type:
Confitem|None- Returns:
The matching
Confitem, orNonewhen no leaf exists. Section names do not return an item; useget()for section snapshots.
- set(key, value)#
Store a user-origin value.
- Parameters:
key (
str) – Scalar key, dotted nested key, or section name whenvalueis an arbitrary-depth mapping.value (
Any) – Python value to store. Nested dictionaries are flattened into dotted leaves and merged with compatible sections. Empty mappings can acquire descendants; assigning an empty mapping to a populated section preserves its descendants. Delete a path before changing between mapping and non-mapping structure. Other leaf type changes remain allowed.
- Raises:
ValueError – If paths contain empty segments, duplicate logical keys, or mapping/non-mapping conflicts at any depth. Rejected mapping assignments leave effective entries unchanged.
- delete(key)#
Remove an effective terminal or every descendant of a section.
Returns true when at least one entry was removed, including null-valued entries, and false for a missing key. With
reload=True, read the current file first and persist through comment-preservingsave(). A failed automatic save restores the entries before deletion.Deletion does not create a defaults tombstone: a later load or reset can supply a deleted default again. Invalid key shapes raise ValueError.
- Return type:
bool- Parameters:
key (str)
- __getitem__(key)#
Return
get(key)so missing keys produceNone.- Parameters:
key (str)
- __setitem__(key, value)#
Assign through
set(key, value).- Parameters:
key (str)
value (Any)
- to_str()#
Reserved for a future detailed printable representation.
- edit_file(*, template=None, backup=None)#
Edit exact file text transactionally in the embedded terminal editor.
F2 or F3 validates and accepts text; Ctrl+Q cancels, confirming discard if changed. Escape dismisses interactions; F1 shows help, F4 opens Find, and F5 opens Find/Replace. Invalid candidates stay in the same session. Only accepted valid text is installed, without reserialization. Cancellation preserves destination content and live entries, including unsaved values.
- Parameters:
template (
str|Path|None) – Seed a missing target with this file’s exact content. This edit-only template does not change configured defaults. Explicit acceptance creates the target even if text is unchanged. Existing targets ignore this argument.backup (
bool|None) –Noneinherits the instance policy. When enabled, copy the existing file after acceptance and validation, immediately before installation. Cancellation creates no backup.
- Returns:
The current
Confeaseinstance.- Raises:
FileNotFoundError – If the instance has no configured path or a template needed for a missing target does not exist.
ValueError – If a needed template is invalid or line endings are mixed.
RuntimeError – If no interactive terminal is available.
Exception – If the editor or installation fails.
Notes
With
autoload=False, a fresh instance can repair malformed text without ordinary destination loading. Cancellation preserves deferred state; successful installation satisfies initialization. Accepted candidates are retained with a recovery path in exception notes on installation failure. Missing-target installation refuses to overwrite a target created during editing. An explicitly assigned externalTextEditorretains direct-file editing, pre-launch backup, and invalid-saved-bytes behavior, with best-effort template drafts for non-Vim/Neovim commands.
- load_sources(cli=None, *files, preference=None)#
Reload file, environment, and CLI sources.
Sources are loaded in file, environment, then CLI order. When the same key appears more than once, the configured origin preference determines the effective value.
- Parameters:
cli (
Namespace|None) – Optionalargparse.Namespacewhose non-Nonevalues are loaded withCLIorigin.*files – Additional config files. Files under the current user’s home directory are
USRorigin; all others areSYSorigin.preference (
list[str] |None) – Optional source precedence override.
- Raises:
FileNotFoundError – If any file path does not exist.
ValueError – If a file suffix, preference, or key shape is invalid.
- reload_files(*paths)#
Load additional config files as system or user origins.
- Parameters:
*paths – Config file paths. Parser selection is inferred from each suffix.
- Raises:
FileNotFoundError – If a path does not exist.
ValueError – If a suffix is unsupported or loaded keys collide.
- reload_cli(namespace)#
Load non-
Noneargparse namespace values as CLI-origin entries.- Parameters:
namespace (
Namespace) – Parsed command-line namespace. Attribute names become config paths, and nested dictionaries are flattened recursively.
- reload_env()#
Load known environment variables as ENV-origin entries.
Only keys already present in defaults or loaded entries are considered. Values are parsed with
yaml.safe_loadso common scalar text such astrue,5432,null, or[1, 2]becomes the corresponding Python value.
Confitem#
- class confease.Confitem(key, value, origin)#
Single flattened configuration value with its source origin.
Confeasestores effective configuration asConfitemleaves. Nested values use dotted keys such as"database.host"while preserving the original Python value type.- Parameters:
key (str)
value (Any)
origin (str)
- property key#
Return the flattened config key.
- property value#
Return the stored value without coercion.
- property origin#
Return the source origin that provided this value.
- __eq__(other)#
Compare by key for strings or by all fields for other items.
- __repr__()#
Return a developer-friendly representation.
- __str__()#
Return the string form of the stored value.