yayaml package#
yayaml: A package providing tools for working with YAML.
Specifically, it makes it simpler to add custom constructors or representers, and adds a whole suite of constructors for basic Python functions.
Submodules#
yayaml.constructors module#
Defines and registers YAML constructors.
- scalar_node_to_object(loader: BaseLoader, node: Node)[source]#
Attempts to convert the given scalar node to a null (Python None), a bool, an int, or a float object using the corresponding YAML constructor. If those conversions fail, constructs a scalar (which will typically result in a string being returned).
- construct_from_func(loader: BaseLoader, node: Node, *, func: Callable, unpack: bool = True) Any[source]#
A constructor that constructs a scalar, mapping, or sequence from the given node and subsequently applies the given function on it.
- Parameters:
loader – The selected YAML loader
node – The node from which to construct a Python object
func (Callable) – The callable to invoke on the resulting
unpack (bool, optional) – Whether to unpack sequences or mappings into the
funccall
- getenv(loader: BaseLoader, node: Node)[source]#
Retrieves an environment variable by name, optionally with fallback
- getboolenv(loader: BaseLoader, node: Node) bool[source]#
Retrieves an environment variable by name, optionally with fallback, and evaluates it as a boolean.
yayaml.exceptions module#
Custom exceptions and exception handling
- raise_improved_exception(exc: Exception, *, hints: List[Tuple[Callable[[Exception], bool], str]] = []) None[source]#
Improves the given exception by appending one or multiple hint messages.
The
hintsargument should be a list of 2-tuples, consisting of a unary matching function, expecting the exception as only argument, and a hint that is part of the new error message.
- YAML_ERROR_HINTS: List[Tuple[Callable[[Exception], bool], str]] = [(<function <lambda>>, 'Did you include a space after the YAML tag defined in that line?'), (<function add_constructor.<locals>.<lambda>>, 'Check the expression syntax'), (<function add_constructor.<locals>.<lambda>>, 'Check the expression syntax'), (<function add_constructor.<locals>.<lambda>>, 'Check the expression syntax'), (<function <lambda>>, 'Read the error message above for details about the error location.')]#
These are evaluated by
raise_improved_exception()and from withinload_yml().Entries are of the form
(match function, hint string)and can also be added viaadd_yaml_error_hint().
yayaml.io module#
Reading and writing YAML files
- load_yml(path: str, *, mode: str = 'r', encoding: str = 'utf8', improve_errors: bool = True, _yaml: ~ruamel.yaml.main.YAML = <ruamel.yaml.main.YAML object>) Any[source]#
Deserializes a YAML file into a Python object.
Uses the yayaml-internal
ruamel.yaml.YAMLobject for loading and thus supports all registered constructors.- Parameters:
path (str) – The path to the YAML file that should be loaded. A
~in the path will be expanded to the current user’s directory.mode (str, optional) – Read mode for the file at
pathencoding (str, optional) – The encoding to use. Assumes UTF-8 as the default; however, if there is a
UnicodeDecodeError, will try again withencoding=None, thus using the default encoding of the operating system.improve_errors (bool, optional) – Whether to improve error messages that come from the call to
yaml.load. If true, the error message is inspected and hints are appended._yaml (ruamel.yaml.YAML, optional) – If given, will use this YAML object for loading. By default, the yayaml-internal one is used, which supports all registered constructors.
- Returns:
- The result of the data loading. Typically, this will be a dict,
but depending on the structure of the file, it may be some other type, including
None.
- Return type:
Any
- write_yml(d: dict | ~typing.Any, *, path: str, mode: str = 'w', _yaml: ~ruamel.yaml.main.YAML = <ruamel.yaml.main.YAML object>)[source]#
Serialize an object using YAML and store it in a file.
Uses the dantro-internal
ruamel.yaml.YAMLobject for dumping and thus supports all registered representers.
- yaml_dumps(obj: ~typing.Any, *, register_classes: tuple = (), _yaml: ~ruamel.yaml.main.YAML = <ruamel.yaml.main.YAML object>, **dump_params) str[source]#
Serializes the given object using (by default) yayaml’s YAML object.
- Parameters:
obj (Any) – The object to dump
register_classes (tuple, optional) – Additional classes to register
_yaml (ruamel.yaml.YAML, optional) – Which YAML object to use for dumping
**dump_params – Dumping parameters, which will be used to set the attributes of the given YAML object.
- Returns:
The output of serialization
- Return type:
- Raises:
RepresenterError – On failure to serialize the given object
- yaml_dumps_plain(*args, **kwargs)[source]#
Like
yaml_dumps()but will create a completely newruamel.yaml.YAMLobject for dumping, thus not having any of the special constructors and representers registered.The aim of this function is to provide YAML dumping that is not dependent on any package configuration; all parameters can be passed here.
In other words, this function does _not_ use the yayaml’s YAML object for dumping but each time creates a new dumper with fixed settings. This reduces the chance of interference from elsewhere. Compared to the time needed for serialization in itself, the extra time needed to create the new ruamel.yaml.YAML object and register the classes is negligible.
Hint
To use yayaml’s YAML object, use
yaml_dumps()instead.Note
The new YAML object will not have _any_ additional representers available!
yayaml.representers module#
This module implements custom YAML representer functions
- represent_by_type(representer: BaseRepresenter, obj: list | tuple | dict | Any, *, tag: str) Node[source]#
A representer for simple types: sequence-like, mapping-like or scalar
- build_representer(simplify_type: Callable[[Any], list | tuple | dict | Any]) Callable[[BaseRepresenter, Any, str], Node][source]#
Builds a representer function from a type simplification callable.
This factory function creates a representer that first converts the object to a simpler type (list, tuple, dict, or scalar) using the provided
simplify_typefunction, then represents it appropriately.- Parameters:
simplify_type – A callable that takes the object to represent and returns a simplified version. Return a list/tuple for sequence representation, a dict for mapping representation, or any other value for scalar representation.
- Returns:
A representer function suitable for use with
add_representer.
Example
>>> from yayaml import add_representer, build_representer >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y >>> add_representer( ... Point, ... build_representer(lambda pt: [pt.x, pt.y]) ... )
yayaml.tools module#
Various tools
- collapse_whitespace(s: str) str[source]#
Replaces runs (two or more) of whitespace (space, tab, line break) with a single space and strips leading or trailing whitespace.
- eval_simple_math_expr(s: str) int | float[source]#
Evalautes simple mathematical expressions, given by strings.
Supports: +, -, , *, /, e-X, eX, inf, nan
- listgen(*, from_range: list | None = None, unique: bool = False, sort: bool = True, append: list | None = None, remove: list | None = None) List[int][source]#
Generates a list of integer elements.
- Parameters:
from_range (list, optional) – range arguments to use as the basis of the list
unique (bool, optional) – Whether to ascertain uniqueness of elements
sort (bool, optional) – Whether to sort the list before returning
append (list, optional) – Additional elements to append to the list
remove (list, optional) – Elements to remove all occurrences of
- Returns:
The generated list
- Return type:
List[int]
yayaml.yaml module#
This module registers various YAML constructors and representers.
Furthermore, it defines a shared ruamel.yaml.YAML object that can be
imported and used for loading and storing YAML files using the representers and
constructors.
- yaml_safe: YAML = <ruamel.yaml.main.YAML object>#
An explicitly ‘safe’ YAML object
- yaml: YAML = <ruamel.yaml.main.YAML object>#
The default YAML object of yayaml
- _REPRESENTERS: Dict[type, Callable[[BaseRepresenter, Any], Node]] = {<class 'range'>: functools.partial(<function build_representer.<locals>.representer_func>, tag='!range'), <class 'slice'>: functools.partial(<function build_representer.<locals>.representer_func>, tag='!slice')}#
All representers that have been added by yayaml
- _CONSTRUCTORS: Dict[str, Callable[[BaseLoader, Node], Any]] = {'!abs': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!add': functools.partial(<function construct_from_func>, func=<built-in function add>, unpack=True), '!all': functools.partial(<function construct_from_func>, func=<built-in function all>, unpack=False), '!and': functools.partial(<function construct_from_func>, func=<built-in function and_>, unpack=True), '!any': functools.partial(<function construct_from_func>, func=<built-in function any>, unpack=False), '!arange': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!array': functools.partial(<function construct_from_func>, func=<built-in function array>, unpack=False), '!boolenv': <function getboolenv>, '!collapse-whitespace': functools.partial(<function construct_from_func>, func=<function collapse_whitespace>, unpack=False), '!compute': <function expression>, '!concat': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!contains': functools.partial(<function construct_from_func>, func=<built-in function contains>, unpack=True), '!deepcopy': functools.partial(<function construct_from_func>, func=<function deepcopy>, unpack=False), '!env': <function getenv>, '!eq': functools.partial(<function construct_from_func>, func=<built-in function eq>, unpack=True), '!expanduser': functools.partial(<function construct_from_func>, func=<function expanduser>, unpack=False), '!expr': <function expression>, '!expression': <function expression>, '!floordiv': functools.partial(<function construct_from_func>, func=<built-in function floordiv>, unpack=True), '!format': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!ge': functools.partial(<function construct_from_func>, func=<built-in function ge>, unpack=True), '!getboolenv': <function getboolenv>, '!getenv': <function getenv>, '!gt': functools.partial(<function construct_from_func>, func=<built-in function gt>, unpack=True), '!if-else': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!if-unix-else': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!if-windows-else': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!int': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!invert': functools.partial(<function construct_from_func>, func=<built-in function invert>, unpack=True), '!isorted': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!join': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!joinpath': functools.partial(<function construct_from_func>, func=<function join>, unpack=True), '!le': functools.partial(<function construct_from_func>, func=<built-in function le>, unpack=True), '!len': <function get_length>, '!linspace': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!listgen': <function listgen>, '!logspace': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!lt': functools.partial(<function construct_from_func>, func=<built-in function lt>, unpack=True), '!max': functools.partial(<function construct_from_func>, func=<built-in function max>, unpack=False), '!min': functools.partial(<function construct_from_func>, func=<built-in function min>, unpack=False), '!mod': functools.partial(<function construct_from_func>, func=<built-in function mod>, unpack=True), '!mul': functools.partial(<function construct_from_func>, func=<built-in function mul>, unpack=True), '!ne': functools.partial(<function construct_from_func>, func=<built-in function ne>, unpack=True), '!negate': functools.partial(<function construct_from_func>, func=<built-in function neg>, unpack=True), '!neq': functools.partial(<function construct_from_func>, func=<built-in function ne>, unpack=True), '!not': functools.partial(<function construct_from_func>, func=<built-in function not_>, unpack=True), '!oneline': functools.partial(<function construct_from_func>, func=<function collapse_whitespace>, unpack=False), '!or': functools.partial(<function construct_from_func>, func=<built-in function or_>, unpack=True), '!pow': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!prod': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!range': functools.partial(<function construct_from_func>, func=<class 'range'>, unpack=True), '!round': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!slice': functools.partial(<function construct_from_func>, func=<class 'slice'>, unpack=True), '!sorted': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=False), '!split': functools.partial(<function construct_from_func>, func=<function <lambda>>, unpack=True), '!str-to-bool': functools.partial(<function construct_from_func>, func=<function str2bool>, unpack=False), '!sub': functools.partial(<function construct_from_func>, func=<built-in function sub>, unpack=True), '!sum': functools.partial(<function construct_from_func>, func=<built-in function sum>, unpack=False), '!truediv': functools.partial(<function construct_from_func>, func=<built-in function truediv>, unpack=True), '!xor': functools.partial(<function construct_from_func>, func=<built-in function xor>, unpack=True)}#
All constructors that have been added by yayaml
- add_representer(t: type, representer: Callable[[BaseRepresenter, Any, str], Node], *, tag: str | None = None, _yaml: YAML | None = None)[source]#
Adds a representer function for the given type
- add_constructor(tag: str, constructor: Callable[[BaseLoader, Node], Any], *, aliases: List[str] | None = None, hint: str | Tuple[Callable[[Exception], bool], str] | None = None, _yaml: YAML | None = None)[source]#
Adds a constructor function for the given tag and optional aliases.