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 items or 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', 'user', 'system', 'default'), backup=False, items=None, *, autoload=True, _locations=None)#

Configuration container with defaults, persistence, and precedence.

Confease keeps one effective value per key. Values can come from defaults, files, environment variables, or command-line namespaces, and the configured preference decides which origin wins when multiple sources define the same key.

Nested mappings support arbitrary depth and are flattened into dotted Confitem leaves 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)

  • _locations (AppLocations | None)

classmethod for_app(app, filename='config.yaml', **options)#

Bind configuration to an application’s platform locations.

The destination is filename in the application’s user configuration directory ($XDG_CONFIG_HOME/<app> or ~/.config/<app> on Linux and macOS; platformdirs’ native per-user directory on Windows). The same file in every system configuration directory ($XDG_CONFIG_DIRS entries or /etc/xdg on Linux and macOS) is loaded as read-only SYS values; earlier directories win. Malformed or unreadable system files are skipped with a ConfeaseWarning. No directories or files are created until the destination is written.

Parameters:
  • app (str) – Application name; nonempty and without path separators.

  • filename (str) – Bare configuration file name. Its suffix selects the parser unless parser is supplied.

  • **options – Constructor keyword options other than path.

Return type:

Confease

Returns:

An application-bound Confease instance.

Raises:
  • ValueError – If a name is invalid or the suffix has no parser.

  • TypeError – If path is supplied.

property app: str | None#

Return the bound application name, or None for explicit paths.

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. System files of a bound application and every source registered through reload_files(), reload_env(), reload_cli(), or load_sources() are reapplied, so they persist across loads. 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 the user layer: values loaded from the destination plus set() assignments minus deletions, including values shadowed by higher-precedence origins. Values from extra files are never copied. When false, write all effective entries, including defaults and overrides from other origins.

  • backup (bool | None) – None inherits 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 path are 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 items defaults 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. System files and registered sources are reapplied afterwards.

Parameters:

backup (bool | None) – Override the instance backup policy for template restoration. None inherits 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. None inherits 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. System files and registered sources are reapplied over the restored values. Construct with autoload=False to 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 default when 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, or None when no leaf exists. Section names do not return an item; use get() for section snapshots.

set(key, value)#

Store a user-origin value.

Parameters:
  • key (str) – Scalar key, dotted nested key, or section name when value is 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-preserving save(). 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 produce None.

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.

A missing YAML target without template opens with the declared items defaults as commented examples, not the effective configuration. Accepting them unchanged creates a file with no user values; uncommented settings, with their parent sections, become user overrides. Path defaults show user-directory placeholders such as $HOME. Defaults are displayed verbatim, so keep secrets out of items. Constructor templates, other formats, and defaults YAML cannot represent keep an empty buffer. Existing files, including empty ones, always open with their exact contents.

Parameters:
  • template (str | Path | None) – Seed a missing target with this file’s exact content. This edit-only template does not change configured defaults and takes precedence over generated default examples. Explicit acceptance creates the target even if text is unchanged. Existing targets ignore this argument.

  • backup (bool | None) – None inherits the instance policy. When enabled, copy the existing file after acceptance and validation, immediately before installation. Cancellation creates no backup.

Returns:

The current Confease instance.

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. System files and registered sources are reapplied over accepted values. 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 external TextEditor retains 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)#

Register and apply 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. Registered sources persist for the lifetime of the instance and are reapplied whenever configuration is rebuilt by load(), automatic reload, editing, reset(), or restore().

Parameters:
  • cli (Namespace | None) – Optional argparse.Namespace whose non-None values are loaded with CLI origin.

  • *files – Additional config files. Files inside the bound application’s user configuration directory are USR origin; all others, and all files of instances without an application, are SYS.

  • 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)#

Register additional config files as system or user origins.

Files inside the bound application’s user configuration directory are USR origin; every other file, and every file of an instance without an application, is SYS. All files are validated before any is registered or applied. Registered files are read again on every rebuild; one that later becomes missing, unreadable, or malformed is skipped with a ConfeaseWarning. Supplying a registered file again makes it the latest registration.

Parameters:

*paths (str | Path) – 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.

Return type:

None

reload_cli(namespace)#

Register non-None argparse namespace values as CLI-origin entries.

Values accumulate across calls, later values winning per key, and are reapplied on every rebuild.

Parameters:

namespace (Namespace) – Parsed command-line namespace. Attribute names become config paths, and nested dictionaries are flattened recursively.

reload_env()#

Register environment variables as an ENV-origin source.

Only keys already present in defaults or loaded entries are considered. Values are parsed with yaml.safe_load so common scalar text such as true, 5432, null, or [1, 2] becomes the corresponding Python value. The environment is read again on every rebuild.

Confitem#

class confease.Confitem(key, value, origin)#

Single flattened configuration value with its source origin.

Confease stores effective configuration as Confitem leaves. 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.