Module attrbox.config

Configuration loading and parsing.

Global variables

var PYTHON_KEYWORDS : Sequence[str]
var LoaderFunc

Function signature to load configuration from a string.

var LOADERS : dict[str, typing.Callable[[str], typing.Any]]

Mapping of file extensions to configuration loaders.

Functions

def set_loader(suffix: str, loader: Callable[[str], Any]) ‑> None

Register a configuration loader for a given file suffix.

NOTE: This will overwrite any previously registered loader for suffix.

Args

suffix : str
file suffix with the leading period (e.g., ".json")
loader : LoaderFunc
function that takes a string and returns an object, typically a Dict[str, Any] of key/value pairs.
def load_config(path: pathlib._local.Path, /, *, load_imports: bool = True, loaders: Optional[dict[str, typing.Callable[[str], typing.Any]]] = None, done: Optional[list[pathlib._local.Path]] = None) ‑> dict[str, typing.Any]

Load a configuration file from path using configuration loaders.

Args

path : Path
file to load.
load_imports : bool, optional
If True, recursively load any files located at the imports key. Defaults to True.
loaders : dict[str, LoaderFunc], optional
mapping of file suffixes to to loader functions. If None, uses the global LOADERS. Defaults to None.
done : list[Path], optional
If provided, a list of paths to ignore when doing recursive loading. Defaults to None.

Returns

dict[str, Any]
keys/values from the configuration file

Examples

>>> root = Path(__file__).parent.parent.parent
>>> expected = {'section': {'key': 'value1', "env": "loaded",
... "json": "loaded", "toml": "loaded"}}
>>> load_config(root / "test/config_1.toml") == expected
True
def optvar(name: str, /, *, shadow_keywords: bool = False, shadow_builtins: bool = False) ‑> str

Return a valid python variable name from a docopt flag.

Args

name : str
docopt option name.
shadow_keywords : bool, optional
If True, allow name to be a python keyword. Otherwise, add an underscore. Defaults to False.
shadow_builtins : bool, optional
If True allow name to be a name of a python builtins (globally available names). Otherwise, add an underscore. Defaults to False.

Returns

str
option name converted to a valid python variable name

Examples

Special cases:

>>> optvar("-") == "stdin"
True
>>> optvar("--") == "__"
True

Leading dashes removed:

>>> optvar("--example") == "example"
True
>>> optvar("-v") == "v"
True

Hyphens become underscores:

>>> optvar("--two-words") == "two_words"
True

Angle brackets removed:

>>> optvar("<file>") == "file"
True

By default, we don't shadow keywords or builtins:

>>> optvar("--continue") == "continue_"
True
>>> optvar("--help") == "help_"
True

Shadow builtins if you want:

>>> optvar("--list", shadow_builtins=True) == "list"
True

Shadow keywords at your own risk:

>>> optvar("--continue", shadow_keywords=True) == "continue"
True
def parse_docopt(doc: str, /, argv: Optional[Sequence[str]] = None, *, version: str = '1.0.0', options_first: bool = False, read_config: bool = True) ‑> AttrDict

Parse docopt args and load config.

Args

doc : str
docstring with description of command
argv : Sequence[str], optional
arguments to parse against the doc. If None, will default to sys.argv[1:]. Defaults to None.
version : str, optional
program version. Defaults to "1.0.0".
options_first : bool
If True, options must come before positional arguments. Defaults to False.
read_config : bool
If True, a <config> argument or --config option will be automatically loaded before args are parsed. Defaults to True.

Returns

AttrDict[str, Any]
mapping of options to values

Examples

>>> usage = "Usage: test.py [--debug]"
>>> parse_docopt(usage, argv=["--debug"])
{'debug': True}
>>> root = Path(__file__).parent.parent.parent
>>> path = str(root / "test/config_1.toml")
>>> usage = "Usage: test.py <config> [--section.key=VAL]"
>>> argv = [path, "--section.key=overwrite"]
>>> expected = {"section": {
...     "key": "overwrite", # overwritten by argv
...     "env": "loaded", "json": "loaded", "toml": "loaded"
... }, "config": path}
>>> parse_docopt(usage, argv=argv) == expected
True