Backends
The base contract every backend implements, followed by each built-in format backend.
Base contract
yaconfiglib.backends.base.ConfigBackend
Bases: Protocol
Base contract for a pluggable configuration format backend.
A backend is responsible for turning a source (typically a file path,
but also strings, streams, or in-memory data depending on the backend)
into a Python object — usually a dict. Backends are looked up and
instantiated automatically by :class:~yaconfiglib.loader.ConfigLoader
based on either an explicit loader= name/instance or by matching
:attr:PATHNAME_REGEX against the source path.
To implement a new backend, subclass :class:ConfigBackend and override
:meth:load (required) and optionally :meth:dumps (for round-trip
serialization support). Subclasses are auto-discovered — simply
importing the module that defines the subclass registers it; no
explicit registry call is needed. See yaconfiglib.backends for the
built-in implementations (YAML, TOML, JSON, INI, dotenv, env, command,
python, jinja2).
Class attributes
PATHNAME_REGEX: Compiled regex matched against a path's filename
(or, for scheme-based backends like CommandBackend, the
full path string) to decide whether this backend can handle a
given source. Set to None for backends that are only
selected explicitly by name (e.g. EnvVarBackend).
NAME: Explicit registry name used by loader="name" lookups. If
unset, the name is derived from the class name by lowercasing
it and stripping a trailing Loader/Config suffix.
DEFAULT_ENCODING: Text encoding used when a backend reads a file
and no explicit encoding= is supplied.
DEFAULT_PATH_FACTORY: Path constructor used to build path objects
when the caller passes a bare string rather than a Path.
DEFAULT_ENCODING = 'utf-8'
class-attribute
instance-attribute
DEFAULT_PATH_FACTORY = _LocalPath
class-attribute
instance-attribute
NAME = None
class-attribute
instance-attribute
PATHNAME_REGEX = None
class-attribute
instance-attribute
__call__(*args, **kwds)
Dispatch to :meth:_yaml_tag_constructor when used as a PyYAML tag constructor.
This lets a backend instance be registered directly with
yaml.Loader.add_constructor (e.g. for !include/!load
tags) — PyYAML calls constructors as constructor(loader, node),
which this method recognizes and routes accordingly.
Source code in src/yaconfiglib/backends/base.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
__subclasses__(*, recursive=False)
classmethod
Return direct (or, if recursive, all transitive) subclasses.
Overrides :meth:type.__subclasses__ to add the recursive flag,
which :meth:get_class_by_name and :meth:get_class_by_path use
to discover every registered backend regardless of how deep its
class hierarchy is.
Source code in src/yaconfiglib/backends/base.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
can_load_path(path)
classmethod
Return True if this backend's :attr:PATHNAME_REGEX matches path's filename.
Source code in src/yaconfiglib/backends/base.py
176 177 178 179 180 181 182 183 | |
dumps(data, **options)
Serialize data back to this backend's text format.
Optional — only needed for backends used with
:func:yaconfiglib.dump/:func:yaconfiglib.dumps. Raises
:class:NotImplementedError by default.
Source code in src/yaconfiglib/backends/base.py
123 124 125 126 127 128 129 130 | |
get_class_by_name(name)
classmethod
Look up a registered backend class by its :attr:NAME.
Falls back to a derived name (lowercased class name with a
trailing Loader/Config suffix stripped) for backends that
don't set :attr:NAME explicitly. Used when a caller passes
loader="yaml" (or similar) instead of a backend instance.
Source code in src/yaconfiglib/backends/base.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
get_class_by_path(path)
classmethod
Find the first registered backend class whose :meth:can_load_path matches path.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If no registered backend claims path. |
Source code in src/yaconfiglib/backends/base.py
185 186 187 188 189 190 191 192 193 194 195 | |
load(path, **options)
Read path and return the parsed configuration object.
Subclasses must override this. Implementations typically accept
additional keyword-only options specific to their format (e.g.
encoding); unrecognized options should generally be ignored via
**options rather than raising, since :class:~yaconfiglib.loader.ConfigLoader
forwards a shared set of options to every backend it invokes.
Source code in src/yaconfiglib/backends/base.py
103 104 105 106 107 108 109 110 111 112 | |
load_all(path, **options)
Yield one or more parsed documents from path.
The default implementation yields a single document produced by
:meth:load. Backends that support multi-document sources (e.g. a
directory or a multi-document YAML stream) should override this.
Source code in src/yaconfiglib/backends/base.py
114 115 116 117 118 119 120 121 | |
YAML
yaconfiglib.backends.yaml.YamlConfig
Bases: ConfigBackend
Backend for *.yaml/*.yml files.
Automatically registers !include and !load tag constructors on
the active PyYAML loader class so nested configuration files can be
pulled in directly from YAML, e.g. database: !include "db.toml".
Registration happens once per loader class and only when a parent
:class:~yaconfiglib.loader.ConfigLoader is supplied via loader=.
DEFAULT_DUMPER_CLS = yaml.Dumper
class-attribute
instance-attribute
DEFAULT_LOADER_CLS = yaml.SafeLoader
class-attribute
instance-attribute
PATHNAME_REGEX = re.compile('.*\\.((yaml)|(yml))$', re.IGNORECASE)
class-attribute
instance-attribute
dumps(data, dumper_cls=None, **options)
Serialize data to a YAML string using dumper_cls (defaults to :attr:DEFAULT_DUMPER_CLS).
Source code in src/yaconfiglib/backends/yaml.py
165 166 167 168 | |
load(path, encoding=None, master=None, loader_cls=None, path_factory=None, loader=None, **options)
Parse path as YAML and return the resulting object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
File to parse, either a |
required |
encoding
|
str
|
Text encoding, defaults to :attr: |
None
|
master
|
Loader
|
An in-progress PyYAML loader instance to inherit
anchors/aliases from — used when this call originates from
a |
None
|
loader_cls
|
type[Loader]
|
PyYAML loader class to use. Defaults to master's
class if given, else :attr: |
None
|
path_factory
|
type[Path]
|
Path constructor used when path is a string. |
None
|
loader
|
ConfigBackend
|
The parent :class: |
None
|
Returns:
| Type | Description |
|---|---|
object
|
The parsed YAML document (typically a |
object
|
scalar). |
Source code in src/yaconfiglib/backends/yaml.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
TOML
yaconfiglib.backends.toml.TomlConfig
Bases: ConfigBackend
Backend for *.toml files.
Uses the standard library :mod:tomllib on Python 3.11+, falling back
to the third-party toml package on older interpreters.
PATHNAME_REGEX = re.compile('.*\\.toml$', re.IGNORECASE)
class-attribute
instance-attribute
load(path, encoding, **kwargs)
Parse path as TOML and return the resulting dict.
Source code in src/yaconfiglib/backends/toml.py
27 28 29 | |
JSON
yaconfiglib.backends.json.JsonConfig
Bases: ConfigBackend
Backend for *.json files, parsed via the standard library :mod:json module.
PATHNAME_REGEX = re.compile('.*\\.json$', re.IGNORECASE)
class-attribute
instance-attribute
dumps(data, **options)
Serialize data to a JSON string via :func:json.dumps.
Source code in src/yaconfiglib/backends/json.py
40 41 42 | |
load(path, encoding=None, json_decoder_options=None, **options)
Parse path as JSON and return the resulting object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File to parse. |
required |
encoding
|
str
|
Text encoding, defaults to :attr: |
None
|
json_decoder_options
|
dict
|
Extra keyword arguments forwarded to
:func: |
None
|
Source code in src/yaconfiglib/backends/json.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
INI
yaconfiglib.backends.ini.IniConfig
Bases: ConfigBackend
Backend for *.ini files, parsed via the standard library's :class:configparser.ConfigParser.
Returns a {section_name: {key: value}} mapping. All values are
strings, matching :mod:configparser semantics — use interpolation
(:func:yaconfiglib.utils.jinja2.interpolate) or manual coercion if
typed values are needed.
DEFAULT_SECTION = 'DEFAULT'
class-attribute
instance-attribute
PATHNAME_REGEX = re.compile('.*\\.ini$', re.IGNORECASE)
class-attribute
instance-attribute
load(path, encoding=None, **options)
Parse path as INI and return a {section: {key: value}} dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File to parse. |
required |
encoding
|
str
|
Text encoding, defaults to :attr: |
None
|
**options
|
object
|
Accepts |
{}
|
Source code in src/yaconfiglib/backends/ini.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
dotenv
yaconfiglib.backends.dotenv.DotenvBackend(lowercase=True)
Bases: ConfigBackend
Parses .env files into a flat {KEY: value} mapping.
Supports:
* KEY=value and export KEY=value syntax
* Single- and double-quoted values
* # comment lines and inline comments (outside quoted values)
Source code in src/yaconfiglib/backends/dotenv.py
66 67 | |
NAME = 'dotenv'
class-attribute
instance-attribute
PATHNAME_REGEX = re.compile('.*\\.env(\\..+)?$', re.IGNORECASE)
class-attribute
instance-attribute
lowercase = lowercase
instance-attribute
load(path, encoding=None, path_factory=None, lowercase=None, **_options)
Parse path as a .env file into a flat {key: value} dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
File to parse, either a |
required |
encoding
|
str
|
Text encoding, defaults to :attr: |
None
|
path_factory
|
Callable[[str], Path]
|
Path constructor used when path is a string. |
None
|
lowercase
|
bool | None
|
Overrides the instance's lowercase for this call. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
A flat mapping of variable name to string value. Values are |
dict[str, str]
|
not coerced to other types — quoting is stripped but the |
dict[str, str]
|
result stays all-string, matching dotenv conventions. |
Source code in src/yaconfiglib/backends/dotenv.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
Environment variables
yaconfiglib.backends.env.EnvVarBackend(prefix='', lowercase=True, nested_delimiter=None, coerce=False)
Bases: ConfigBackend
Exposes os.environ (or a subset) as a configuration document.
Parameters
prefix: When given, only variables whose names start with prefix are included. The prefix is stripped from the key names. lowercase: If True (default) convert key names to lowercase for consistency with YAML/TOML conventions.
Source code in src/yaconfiglib/backends/env.py
73 74 75 76 77 78 79 80 81 82 83 | |
NAME = 'env'
class-attribute
instance-attribute
PATHNAME_REGEX = None
class-attribute
instance-attribute
coerce = coerce
instance-attribute
lowercase = lowercase
instance-attribute
nested_delimiter = nested_delimiter
instance-attribute
prefix = prefix
instance-attribute
load(path=None, prefix=None, lowercase=None, nested_delimiter=None, coerce=None, **_options)
Snapshot os.environ (optionally filtered/coerced) into a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
Ignored — present only so this backend satisfies the
:meth: |
None
|
prefix
|
str | None
|
Overrides the instance's prefix for this call. |
None
|
lowercase
|
bool | None
|
Overrides the instance's lowercase for this call. |
None
|
nested_delimiter
|
str | None
|
Overrides the instance's nested_delimiter.
When set, keys containing the delimiter (after prefix
stripping) are split into nested dicts, e.g. with
delimiter |
None
|
coerce
|
bool | None
|
Overrides the instance's coerce. When True, string
values are converted to |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
A flat or nested dict depending on nested_delimiter. |
Source code in src/yaconfiglib/backends/env.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
Commands and scripts
yaconfiglib.backends.command.CommandBackend
Bases: ConfigBackend
Executes a script/command and parses stdout into a configuration object.
Sources are recognized either by a URI scheme prefix (exec://,
cmd://, sh://, or a format-tagged variant like cmd+json://)
or by a .sh/.bat/.ps1/.cmd file extension. The command
is run through the shell and its stdout is parsed as configuration
data — this makes it easy to source secrets or dynamic values from
external tools, e.g. cmd+json://aws secretsmanager get-secret-value ....
Output format resolution, in priority order:
- An explicit
format=argument. - The
+fmtsuffix on the scheme (e.g.cmd+yaml://...). - A
#!fmtshebang line at the start of the command's stdout. - Sniffing: try json, yaml, toml, dotenv, ini in turn.
If parsing fails and no format was requested, the raw stdout string is returned as a fallback rather than raising.
NAME = 'command'
class-attribute
instance-attribute
PATHNAME_REGEX = re.compile('^(exec|cmd|sh|exec\\+\\w+|cmd\\+\\w+)(://|:\\\\|:/|:).*|.*?\\.(sh|bat|ps1|cmd)$', re.IGNORECASE)
class-attribute
instance-attribute
can_load_path(path)
classmethod
Return True if path matches a command scheme prefix or script extension.
Source code in src/yaconfiglib/backends/command.py
46 47 48 49 50 51 52 53 | |
load(path, encoding=None, format=None, path_factory=None, **options)
Run the command encoded in path and parse its stdout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
A scheme-prefixed command string (e.g.
|
required |
encoding
|
str
|
Codec used to decode the command's stdout/stderr
(default |
None
|
format
|
str | list[str]
|
Explicit output format, or a comma-separated/list of candidate formats to try in order. Overrides shebang detection and sniffing. |
None
|
path_factory
|
Callable[[str], Path]
|
Unused; accepted for interface consistency. |
None
|
Returns:
| Type | Description |
|---|---|
object
|
The parsed stdout, or the raw stripped stdout string if no |
object
|
format could be determined and sniffing failed. |
Raises:
| Type | Description |
|---|---|
CalledProcessError
|
If the command exits non-zero. |
ValueError
|
If an explicit format/shebang format is requested but the output cannot be parsed as that format, or output is empty while a format was requested. |
Source code in src/yaconfiglib/backends/command.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
In-memory Python objects
yaconfiglib.backends.python_backend.PythonBackend(data=None)
Bases: ConfigBackend
Wraps a plain Python object (dict, list, etc.) as a config source.
Useful for injecting computed or in-memory configuration into a loader chain without writing a file::
loader.load(
"base.yaml",
PythonBackend({"override_key": "override_value"}),
)
Source code in src/yaconfiglib/backends/python_backend.py
32 33 | |
NAME = 'python'
class-attribute
instance-attribute
PATHNAME_REGEX = None
class-attribute
instance-attribute
load(path=None, **_options)
Return the wrapped object, ignoring any file I/O.
If constructed with data=..., that object is always returned.
Otherwise path itself is returned as-is, letting this backend
double as a passthrough for already-parsed data injected into a
loader chain.
Source code in src/yaconfiglib/backends/python_backend.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
Jinja2-templated sources
yaconfiglib.backends.jinja2.Jinja2ConfigLoader
Bases: ConfigBackend
Backend for *.j2/*.jinja2 template sources.
Renders the file as a Jinja2 template first, then dispatches the
rendered text to whichever backend matches the un-templated filename
(e.g. settings.yaml.j2 renders through Jinja2 and is then parsed as
YAML). This lets any existing format be templated by simply appending
a .j2/.jinja2 suffix, without needing a dedicated templated
variant of each backend.
The rendered output is written to an in-memory path (MemPath, or a
real temp file when pathlib_next is unavailable) before being
handed to the resolved backend, so downstream backends see ordinary
file content and don't need any Jinja2-specific handling.
NAME = 'jinja2'
class-attribute
instance-attribute
PATHNAME_REGEX = re.compile('.*\\.((j2)|(jinja2))$', re.IGNORECASE)
class-attribute
instance-attribute
load(path, encoding=None, loader=None, environment=None, **kwargs)
Render path as a Jinja2 template, then load the result with the matching backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the |
required |
encoding
|
str
|
Text encoding for reading the template and writing
the rendered output. Defaults to :attr: |
None
|
loader
|
ConfigBackend
|
The parent :class: |
None
|
environment
|
Environment
|
A :class: |
None
|
Returns:
| Type | Description |
|---|---|
None
|
The parsed object produced by the backend matching the |
None
|
rendered filename (with the |
None
|
stripped). |
Source code in src/yaconfiglib/backends/jinja2.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |