fagus package

Library to easily create, edit and traverse nested objects of dicts and lists in Python

The following objects can be imported directly from this module:
  • Fagus: a wrapper-class for complex, nested objects of dicts and lists

  • Fil, CFil and VFil are filter-objects that can be used to filter Fagus-objects

  • INF: alias for sys.maxsize, used e.g. to indicate that an element should be appended to a list

Submodules in fagus:
class fagus.Fagus(root: Optional[Collection[Any]] = None, node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, default_node_type: OptStr = Ellipsis, default: OptAny = Ellipsis, if_: OptAny = Ellipsis, iter_fill: OptAny = Ellipsis, mod_functions: Union[Mapping[Union[type, Tuple[type], str], Callable[[Any], Any]], ellipsis] = Ellipsis, copy: bool = False)

Bases: MutableMapping, MutableSequence, MutableSet

Fagus is a wrapper-class for complex, nested objects of dicts and lists in Python

Fagus can be used as an object by instantiating it, but it’s also possible to use all methods statically without even an object, so that a = {}; Fagus.set(a, "top med", 1) and a = Fagus({}); a.set(1, "top med") do the same.

The root node is always modified directly. If you don’t want to change the root node, all the functions where it makes sense support to rather modify a copy, and return that modified copy using the copy-parameter.

FagusOptions: Several parameters used in functions in Fagus work as options so that you don’t have to specify them each time you run a function. In the docstrings, these options are marked with a *, e.g. the fagus parameter is an option. Options can be specified at three levels with increasing precedence: at class-level (Fagus.fagus = True), at object-level (a = Fagus(), a.fagus = True) and in each function-call (a.get("b", fagus=True)). If you generally want to change an option, change it at class-level - all objects in that file will inherit this option. If you want to change the option specifically for one object, change the option at object-level. If you only want to change the option for one single run of a function, put it as a function-parameter. More thorough examples of options can be found in README.md.

__init__(root: Optional[Collection[Any]] = None, node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, default_node_type: OptStr = Ellipsis, default: OptAny = Ellipsis, if_: OptAny = Ellipsis, iter_fill: OptAny = Ellipsis, mod_functions: Union[Mapping[Union[type, Tuple[type], str], Callable[[Any], Any]], ellipsis] = Ellipsis, copy: bool = False)

Constructor for Fagus, a wrapper-class for complex, nested objects of dicts and lists in Python

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • root – object (like dict / list) to wrap Fagus around. If this is None, an empty node of the type default_node_type will be used. Default None

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * this option is used to determine whether nodes in the returned object should be returned as Fagus-objects. This can be useful e.g. if you want to use Fagus in an iteration. Check the particular function you want to use for a more thorough explanation of what this does in each case

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • default – * ~ is used in get and other functions if a path doesn’t exist

  • if_ – * only set value if it meets the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check value)

  • iter_fill – * Fill up tuples with iter_fill (can be any object, e.g. None) to ensure that all the tuples iter() returns are exactly max_items long. See iter()

  • mod_functions – * ~ is used to define how different types of objects are supposed to be serialized. This is defined in a dict. The keys are either a type (like IPAddress) or a tuple of different types (IPv4Address, IPv6Address). The values are function pointers, or lambdas, which are supposed to convert e.g. an IPv4Address into a string. Check out TFunc if you want to call more complicated functions with several arguments. See README for examples

  • copy – ~ creates a copy of the root node before Fagus is initialized. Makes sure that changes on this Fagus won’t modify the root node that was passed here itself. Default False

root: Collection[Any]

Contains the root note the Fagus-object is wrapped around

This can be used to remove the Fagus-wrapper in case the plain object is needed, e.g. if a = Fagus(["ex"]), a.root = ["ex"]. The root node is also returned when a is called: a(), examples in Fagus.__call__().

get(path: Any = '', default: OptAny = Ellipsis, fagus: OptBool = Ellipsis, copy: bool = False, path_split: OptStr = Ellipsis) Any

Retrieves value at path. If the value doesn’t exist, default is returned.

To get "hello" from x = Fagus({"a": ["b", {"c": "d"}], e: ["f", "g"]}), you can use x[("a", 1, "c")]. The tuple ("a", 1, "c") is the path-parameter that is used to traverse x. At first, the list at "a" is picked in the top-most dict, and then the 2nd element {"c": "d"} is picked from that list. Then, “d” is picked from {"c": "d"} and returned. The path-parameter can be a tuple or list, the keys must be either integers for lists, or any hashable objects for dicts. For convenience, the keys can also be put in a single string separated by path_split (default " "), so a["a 1 c"] also returns "d".

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – List/Tuple of key-values to recursively traverse self. Can also be specified as string, that is split into a tuple using path_split

  • default – * returned if path doesn’t exist in self

  • fagus – * returns a Fagus-object if the value at path is a list or dict

  • copy – Option to return a copy of the returned value. The default behaviour is that if there are subnodes (dicts, lists) in the returned values, and you make changes to these nodes, these changes will also be applied in the root node from which values() was called. If you want the returned values to be independent, use copy to get a shallow copy of the returned value

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

the value if the path exists, or default if it doesn’t exist

iter(max_depth: int = 9223372036854775807, path: Any = '', filter_: Optional[Fil] = None, fagus: OptBool = Ellipsis, iter_fill: OptAny = Ellipsis, select: Optional[Union[int, Iterable[Any]]] = None, copy: bool = False, iter_nodes: OptBool = Ellipsis, filter_ends: bool = False, path_split: OptStr = Ellipsis) FagusIterator

Recursively iterate through Fagus-object, starting at path

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • max_depth – Can be used to limit how deep the iteration goes. Example: a = {"a": ["b", ["c", "d"]], "e": "f"} If max_depth is sys.max_size, all the nodes are traversed: [("a", "b", "c"), ("a", "b", "d"]), ("e", "f")]. If max_depth is 1, iter returns [("a", "b", ["c", "d"]), ("e", "f")], so ["c", "d"] is not iterated through but returned as a node. If max_depth is 0, iter returns [("a", ["b", ["c", "d"]]), ("e", "f")], effectively the same as dict.items(). Default sys.maxitems (iterate as deeply as possible). A negative number (e.g. -1) is treated as sys.maxitems.

  • path – Start iterating at path. Internally calls get(path), and iterates on the node get returns. See get()

  • filter_ – Only iterate over specific nodes defined using Fil (see README.md and Fil for more info)

  • fagus – * If the leaf in the tuple is a dict or list, return it as a Fagus-object. This option has no effect if max_items is sys.maxitems.

  • iter_fill – * Fill up tuples with iter_fill (can be any object, e.g. None) to ensure that all the tuples iter() returns are exactly max_items long. This can be useful if you want to unpack the keys / leaves from the tuples in a loop, which fails if the count of items in the tuples varies. This option has no effect if max_items is -1. The default value is …, meaning that the tuples are not filled, and the length of the tuples can vary. See README for a more thorough example.

  • select – Extract only some specified values from the tuples. E.g. if ~ is -1, only the leaf-values are returned. ~ can also be a list of indices. Default None (don’t reduce the tuples)

  • copy – Iterate on a shallow-copy to make sure that you can edit root node without disturbing the iteration

  • iter_nodes – * includes the traversed nodes into the resulting tuples, order is then: node1, key1, node2, key2, …, leaf_value

  • filter_ends – Affects the end dict/list that is returned if max_items is used. Normally, filters are not applied on that end node. If you would like to get the end node filtered too, set this to True. If this is set to True, the last nodes will always be copies (if unfiltered they are references)

  • path_split – * used to split path into a list if path is a str, default " ", see README

Returns:

FagusIterator with one tuple for each leaf-node, containing the keys of the parent-nodes until the leaf

filter(filter_: Fil, path: Any = '', fagus: OptBool = Ellipsis, copy: bool = False, default: OptAny = Ellipsis, path_split: OptStr = Ellipsis) Collection[Any]

Filters self, only keeping the nodes that pass the filter

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • filter_ – Fil-object in which the filtering-criteria are specified

  • path – at this point in self, the filtering will start (apply filter_ relatively from this point). Default "", meaning that the root node is filtered, see get() and README for examples

  • fagus – * return the filtered self as Fagus-object (default is just to return the filtered node)

  • copy – Create a copy and filter on that copy. Default is to modify the self directly

  • default – * returned if path doesn’t exist in self, or the value at path can’t be filtered

  • path_split – * used to split path into a list if path is a string, default " ", see README

Returns:

the filtered object, starting at path

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

split(filter_: Optional[Fil], path: Any = '', fagus: OptBool = Ellipsis, copy: bool = False, default: OptAny = Ellipsis, path_split: OptStr = Ellipsis) Union[Tuple[Collection[Any], Collection[Any]], Tuple[Any, Any]]

Splits self into nodes that pass the filter, and nodes that don’t pass the filter

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • filter_ – Fil-object in which the filtering-criteria are specified

  • path – at this position in self, the splitting will start (apply filter_ relatively from this point). Default "", meaning that the root node is split, see get() and README for examples

  • fagus – * return the filtered self as Fagus-object (default is just to return the filtered node)

  • copy – Create a copy and filter on that copy. Default is to modify the object directly

  • default – * returned if path doesn’t exist in self

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

a tuple, where the first element is the nodes that pass the filter, and the second element is the nodes that don’t pass the filter

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

set(value: Any, path: Iterable[Any], node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path, and finally set value at leaf-node

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • value – ~ is placed at path, after creating new nodes if necessary. An existing value at path is overwritten

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only set value if it meets the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check value)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

append(value: Any, path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path, and finally append value to a list at leaf-node

If the leaf-node is a set, tuple or other value it is converted to a list. Then the new value is appended.

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • value – ~ is appended to list at path, after creating new nodes along path as necessary

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only append value if it meets the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check value)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if path is empty and the root node is not a list (can’t append to a dict, tuple or set) or the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

extend(values: Iterable[Any], path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path. Then extend list at leaf-node with the new values

If the leaf-node is a set, tuple or other value it is converted to a list, which is extended with the new values

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • values – the list at path is extended with ~, after creating new nodes along path as necessary

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only extend with values if they meet the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check values)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if path is empty and the root node is not a list (can’t extend a dict, tuple or set) or the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

insert(index: int, value: Any, path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path. Insert new value at index in list at leaf-node

If the leaf-node is a set, tuple or other value it is converted to a list, in which the new value is inserted at index

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • index – ~ at which the value shall be inserted in the list at path

  • value – ~ is inserted at index into list at path, after creating new nodes along path as necessary

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only insert value if it meets the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check value)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if path is empty and the root node is not a list (can’t insert into dict, tuple or set) or the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

add(value: Any, path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path, and finally add new value to set at leaf-node

If the leaf-node is a list, tuple or other value it is converted to a set, to which the new value is added

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • value – ~ is added to set at path, after creating new nodes along path as necessary

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only add value if it meets the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check value)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if path is empty and the root node is not a set (can’t add to list or dict) or the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

update(values: Iterable[Any], path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, if_: OptAny = Ellipsis, default_node_type: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Create (if they don’t already exist) all sub-nodes in path, then update set at leaf-node with new values

If the leaf-node is a list, tuple or other value it is converted to a set. That set is then updated with the new values. If the node at path is a dict, and values also is a dict, the node-dict is updated with the new values.

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • values – the set/dict at path is updated with ~, after creating new nodes along path as necessary

  • path – List/Tuple of key-values that are traversed in self. If no nodes exist at the keys, new nodes are created. Can also be specified as a string, that is split into a tuple using path_split. See get()

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a string, default " ", see README

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • if_ – * only update with values if they meet the condition specified here, otherwise do nothing. The condition can be a lambda, any value or a tuple of accepted values. Default _None (don’t check values)

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

  • copy – if this is set, a copy of self is modified and then returned (thus self is not modified)

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if path is empty and the root node is not a set or dict (can’t update list) or the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

setdefault(path: Any = '', default: OptAny = Ellipsis, fagus: OptBool = Ellipsis, node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, default_node_type: OptStr = Ellipsis) Any

Get value at path and return it. If there is no value at path, set default at path, and return default

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – position in self where default shall be set / from where value shall be fetched. See get() and README

  • default – * returned if path doesn’t exist in self

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a str, default " "

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

Returns:

value at path if it exists, otherwise default is set at path and returned

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

mod(mod_function: Callable[[Any], Any], path: Iterable[Any], default: OptAny = Ellipsis, replace_value: bool = True, fagus: OptBool = Ellipsis, node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, default_node_type: OptStr = Ellipsis) Any

Modifies the value at path using the function-pointer mod_function

mod can be used like this Fagus.mod(obj, “kitchen spoon”, lambda x: x + 1, 1) to count the number of spoons in the kitchen. If there is no value to modify, the default value (here 1) will be set at the node.

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • mod_function – A function pointer or lambda that modifies the existing value at path. TFunc can be used to call more complex functions requiring several arguments.

  • path – position in self at which the value shall be modified. Defined as a list/Tuple of key-values to recursively traverse self. Can also be specified as string which is split into a tuple using path_split

  • default – * this value is set in path if it doesn’t exist

  • fagus – * Return new value as a Fagus-object if it is a node (tuple / list / dict), default False

  • replace_value – Replace the old value with what mod_function returns. Can be deactivated e.g. if mod_function changes the object, but returns None (if ~ stays on, the object is replaced with None). Default True. If no value exists at path, the default value is always set at path (independent of ~)

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a str, default " "

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

Returns:

the new value that was returned by the mod_function, or default if there was no value at path

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

mod_all(mod_function: Callable[[Any], Any], filter_: Optional[Fil] = None, path: Any = '', replace_value: bool = True, default: OptAny = Ellipsis, max_depth: int = 9223372036854775807, fagus: OptBool = Ellipsis, copy: bool = False, path_split: OptStr = Ellipsis) Any

Modify all the leaf-values that match a certain filter

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • mod_function – A function pointer or lambda that modifies the existing value at path. TFunc can be used to call more complex functions requiring several arguments.

  • filter_ – used to select which leaves shall be modified. Default None (all leaves are modified)

  • path – position in self at which the value shall be modified. See get() / README

  • default – * this value is returned if path doesn’t exist, or if no leaves match the filter

  • fagus – * Return new value as a Fagus-object if it is a node (tuple / list / dict), default False

  • replace_value – Replace the old value with what mod_function returns. Can be deactivated e.g. if mod_function changes the object, but returns None (if ~ stays on, the object is replaced with None). Default True. If no value exists at path, the default value is always set at path (independent of ~)

  • max_depth – Defines the maximum depth for the iteration. See Fagus.iter max_depth for more information

  • copy – Can be ued to make sure that the node at path is not modified (instead a modified copy is returned)

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

the node at path where all the leaves matching filter_ are modified, or default if it didn’t exist

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

serialize(mod_functions: Optional[Mapping[Union[type, Tuple[type], str], Callable[[Any], Any]]] = None, path: Any = '', node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, path_split: OptStr = Ellipsis, copy: bool = False) Union[Dict[Any, Any], List[Any]]

Makes sure the object can be serialized so that it can be converted to JSON, YAML etc.

The only allowed data-types for serialization are: dict, list, bool, float, int, str, None

Sets and tuples are converted into lists. Other objects whose types are not allowed in serialized objects are modified to a type that is allowed using the mod_functions-parameter. mod_functions is a dict, with the type of object like IPv4Address or a tuple of types like (IPv4Address, IPv6Address). The values are function pointers or lambdas, that are executed to convert e.g. an IPv4Address to one of the allowed data types mentioned above.

The default mod_functions are: {datetime: lambda x: x.isoformat(), date: lambda x: x.isoformat(), time: lambda x: x.isoformat(), “default”: lambda x: str(x)}

By default, date, datetime and time-objects are replaced by their isoformat-string. All other objects whose types don’t appear in mod_functions are modified by the function behind the key “default”. By default, this function is lambda x: str(x) that replaces the object with its string-representation.

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • mod_functions – * ~ is used to define how different types of objects are supposed to be serialized. This is defined in a dict. The keys are either a type (like IPAddress) or a tuple of different types (IPv4Address, IPv6Address). The values are function pointers, or lambdas, which are supposed to convert e.g. an IPv4Address into a string. Check out TFunc if you want to call more complicated functions with several arguments. See README for examples

  • path – position in self at which the value shall be modified. See get() / README

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • path_split – * used to split path into a list if path is a str, default " "

  • copy – Create a copy and make that copy serializable. Default is to modify self directly

Returns:

a serializable object that only contains types allowed in json or yaml

Raises:
  • TypeError – if root node is not a dict or list (serialize can’t fix that for the root node)

  • ValueError – if tuple_keys is not defined in mod_functions and a dict has tuples as keys

  • Exception – Can raise any exception if it occurs in one of the mod_functions

merge(obj: Union[FagusIterator, Collection[Any]], path: Any = '', new_value_action: str = 'r', extend_from: int = 9223372036854775807, update_from: int = 9223372036854775807, fagus: OptBool = Ellipsis, copy: bool = False, copy_obj: bool = False, path_split: OptStr = Ellipsis, node_types: OptStr = Ellipsis, list_insert: OptInt = Ellipsis, default_node_type: OptStr = Ellipsis) Collection[Any]

Merges two or more tree-objects to update and extend the root node

Parameters:
  • obj – tree-object that shall be merged. Can also be a FagusIterator returned from iter() to only merge values matching a filter defined in iter()

  • path – position in root where the new objects shall be merged, default “”

  • new_value_action – This parameter defines what merge is supposed to do if a value at a path is present in the root and in one of the objects to merge. The possible values are: (r)eplace - the value in the root is replaced with the new value, this is the default behaviour; (i)gnore - the value in the root is not updated; (a)ppend - the old and new value are both put into a list, and thus aggregated

  • extend_from – By default, lists are traversed, so the value at index i will be compared in both lists. If at some point you rather want to just append the contents from the objects to be merged, use this parameter to define the level (count of keys) from which lists should be extended isf traversed. Default infinite (never extend lists)

  • update_from – Like extend_from, but for dicts. Allows you to define at which level the contents of the root should just be updated with the contents of the objects instead of traversing and comparing each value

  • fagus – whether the returned tree-object should be returned as Fagus

  • copy – Don’t modify the root node, modify and return a copy instead

  • copy_obj – The objects to be merged are not modified, but references to subnodes of the objects can be put into the root node. Set this to True to prevent that and keep root and objects independent

  • path_split – * used to split path into a list if path is a str, default " "

  • node_types – * Can be used to manually define if the nodes along path are supposed to be (l)ists or (d)icts. E.g. "dll" to create a dict at level 1, and lists at level 2 and 3. " " can also be used – space doesn’t enforce a node-type like "d" or "l". For " ", existing nodes are traversed if possible, otherwise default_node_type is used to create new nodes. Default "", interpreted as ” ” at each level. See README

  • list_insert – * Level at which a new node shall be inserted into the list instead of traversing the existing node in the list at that index. See README

  • default_node_type – * determines if new nodes by default should be created as (d)ict or (l)ist. Must be either "d" or "l", default "d", examples in README

Returns:

a reference to the modified root node, or a modified copy of the root node (see copy-parameter)

Raises:
  • ValueError – if it isn’t possible to parse an int-index from the provided key in a position where node-types defines that the node shall be a list (if node-types is not l, the node will be replaced with a dict)

  • TypeError – if obj is not either a FagusIterator or a Collection. Also raised if you try to merge different types of nodes at root level, e.g. a dict can only be merged with another Mapping, and a list can only be merged with another Iterable. ~ is also raised if a not modifiable root node needs to be modified

pop(path: Any = '', default: OptAny = Ellipsis, fagus: OptBool = Ellipsis, path_split: OptStr = Ellipsis) Any

Deletes the value at path and returns it

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – pop value at this position in self, or don’t do anything if path doesn’t exist in self

  • default – * returned if path doesn’t exist in self

  • fagus – * return the result as Fagus-object if possible (default is just to return the result)

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

value at path if it exists, or default if it doesn’t

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

popitem() None

This function is not implemented in Fagus

Implementing this would require to cache the value, which was not prioritized to keep memory usage low.

discard(path: Any = '', path_split: OptStr = Ellipsis) None

Deletes the value at path if it exists

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – pop value at this position in self, or don’t do anything if path doesn’t exist in self

  • path_split – * used to split path into a list if path is a str, default " "

Returns: None

remove(path: Any = '', path_split: OptStr = Ellipsis) None

Deletes the value at path if it exists, raises KeyError if it doesn’t

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – pop value at this position in self, or don’t do anything if path doesn’t exist in self

  • path_split – * used to split path into a list if path is a str, default " "

Returns: None

Raises:

KeyError – if the value at path doesn’t exist

keys(path: Any = '', path_split: OptStr = Ellipsis) Iterable[Any]

Returns keys for the node at path, or None if that node is a set or doesn’t exist / doesn’t have keys

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – get keys for node at this position in self. Default "" (gets values from the root node), See get()

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

keys for the node at path, or an empty tuple if that node is a set or doesn’t exist / doesn’t have keys

values(path: Any = '', path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, copy: bool = False) Iterable[Any]

Returns values for node at path

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – get values at this position in self, default “” (gets values from the root node). See get()

  • path_split – * used to split path into a list if path is a str, default " "

  • fagus – * converts sub-nodes into Fagus-objects in the returned list of values, default False

  • copy – ~ creates a copy of the node before values() are returned. This can be beneficial if you want to make changes to the returned nodes, but you don’t want to change self. Default False

Returns:

values for the node at path. Returns an empty tuple if the value doesn’t exist, or just the value in a tuple if the node isn’t iterable.

items(path: Any = '', path_split: OptStr = Ellipsis, fagus: OptBool = Ellipsis, copy: bool = False) Iterable[Any]

Returns in iterator of (key, value)-tuples in self, like dict.items()

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – get items at this position in self, Default "" (gets values from the root node). See get()

  • path_split – * used to split path into a list if path is a str, default " "

  • fagus – * converts sub-nodes into Fagus-objects in the returned iterator, default False

  • copy – ~ creates a copy of the node before items() are returned. This can be beneficial if you want to make changes to the returned nodes, but you don’t want to change self. Default False

Returns:

iterator of (key, value)-tuples in self, like dict.items()

clear(path: Any = '', path_split: OptStr = Ellipsis, copy: bool = False, fagus: OptBool = Ellipsis) Collection[Any]

Removes all elements from node at path.

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – clear at this position in self, Default "" (gets values from the root node). See get()

  • path_split – * used to split path into a list if path is a str, default " "

  • copy – if ~ is set, a copy of self is modified and then returned (thus self is not modified), default False

  • fagus – * return self as a Fagus-object if it is a node (tuple / list / dict), default False

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

contains(value: Any, path: Any = '', path_split: OptStr = Ellipsis) bool

Check if value is present in the node at path

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • value – value to check

  • path – check if value is in node at this position in self, Default "" (checks root node). See get()

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

whether value is in node at path in self. returns value == node if the node isn’t iterable, and false if path doesn’t exit in self

count(path: Any = '', path_split: OptStr = Ellipsis) int

Check the number of elements in the node at path

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – position in self where the number of elements shall be found.Default "" (checks root node). See get() and README for examples

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

the number of elements in the node at path. if there is no node at path, 0 is returned. If the element at path is not a node, 1 is returned

index(value: Any, start: OptInt = Ellipsis, stop: OptInt = Ellipsis, path: Any = '', all_: bool = False, path_split: OptStr = Ellipsis) Optional[Union[int, Any, Sequence[Any]]]

Returns the index / key of the specified value in the node at path if it exists

Parameters:
  • value – ~ to search index for

  • start – start searching at this index. Only applicable if the node at path is a list / tuple

  • stop – stop searching at this index. Only applicable if the node at path is a list / tuple

  • path – position in self where the node shall be searched for value. Default "" (checks root node). See get() and README for examples

  • all_ – returns all matching indices / keys in a generator (instead of only the first)

  • path_split – * used to split path into a list if path is a str, default " "

Returns:

The first index of value if the node at path is a list, or the first key containing value if the node at path is a dict. True if the node at path is a Set and contains value. If the element can’t be found in the node at path, or there is no Collection at path, None is returned (instead of a ValueError).

isdisjoint(other: Iterable[Any], path: Any = '', path_split: OptStr = Ellipsis, dict_: str = 'keys') bool

Returns whether the other iterable is disjoint (has no common items) with the node at path

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • other – other object to check

  • path – check if the node at this position in self, is disjoint from other

  • path_split – * used to split path into a list if path is a str, default " "

  • dict_ – use (k)eys, (v)alues or (i)tems for if value is a dict. Default keys

Returns: whether the other iterable is disjoint from the value at path. If value is a dict, the keys are used.

Checks if value is present in other if value isn’t iterable. Returns True if there is no value at path.

child(obj: Optional[Collection[Any]] = None, **kwargs) Fagus

Creates a Fagus-object for obj that has the same options as self

reversed(path: Any = '', fagus: OptBool = Ellipsis, path_split: OptStr = Ellipsis, copy: bool = False) Iterator[Any]

Get reversed child-node at path if that node is a list

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – position in self where a list / tuple shall be returned reversed

  • fagus – * converts sub-nodes into Fagus-objects in the returned iterator, default False

  • path_split – * used to split path into a list if path is a str, default " "

  • copy – ~ creates a copy of the node before it is returned reversed(). This can be beneficial if you want to make changes to the returned nodes, but you don’t want to change self. Default False

Returns:

a reversed iterator on the node at path (empty if path doesn’t exist)

reverse(path: Any = '', fagus: OptBool = Ellipsis, path_split: OptStr = Ellipsis, copy: bool = False) Collection[Any]

Reverse child-node at path if that node exists and is reversible

* means that the parameter is a FagusOption, see Fagus-class-docstring for more information about options

Parameters:
  • path – position in self where a list / tuple shall be reversed

  • fagus – * converts sub-nodes into Fagus-objects in the returned iterator, default False

  • path_split – * used to split path into a list if path is a str, default " "

  • copy – ~ creates a copy of the node before it is returned reversed(). This can be beneficial if you want to make changes to the returned nodes, but you don’t want to change self. Default False

Returns:

self as a node if fagus is set, or a modified copy of self if copy is set

Raises:

TypeError – if the root node needs to be modified and isn’t modifiable (e.g. tuple or frozenset)

copy(deep: bool = False) Collection[Any]

Creates a copy of self. Creates a recursive shallow copy by default, or a copy.deepcopy() if deep is set.

options(options: Optional[Dict[str, Any]] = None, get_default_options: bool = False, reset: bool = False) Dict[str, Any]

Function to set multiple Fagus-options in one line

Parameters:
  • options – dict with options that shall be set

  • get_default_options – return all options (include default-values). Default: only return options that are set

  • reset – if ~ is set, all options are reset before options is set

Returns:

a dict of options that are set, or all options if get_default_options is set

__copy__(recursive: bool = False) Collection[Any]

Recursively creates a shallow-copy of self

__call__() Collection[Any]

Calling the Fagus-object returns the root node the Fagus-object is wrapped around (equivalent to .root)

Example

>>> from fagus import Fagus
>>> a = Fagus({"f": "q"})
>>> a
Fagus({'f': 'q'})
>>> a()
{'f': 'q'}
>>> a.root  # .root returns the root-object in the same way as ()
{'f': 'q'}
Returns:

the root object Fagus is wrapped around

__getattr__(attr: str) Any
__getitem__(item: Any) Any
__setattr__(attr: str, value: Any) None

Implement setattr(self, name, value).

__setitem__(path: Any, value: Any) None
__delattr__(attr: str) None

Implement delattr(self, name).

__delitem__(path: Any) None
__iter__() Iterator[Any]
__hash__() int

Return hash(self).

__eq__(other: Any) bool

Return self==value.

__ne__(other: Any) bool

Return self!=value.

__lt__(other: Any) bool

Return self<value.

__le__(other: Any) bool

Return self<=value.

__gt__(other: Any) bool

Return self>value.

__ge__(other: Any) bool

Return self>=value.

__contains__(value: Any) bool
__len__() int
__bool__() bool
__repr__() str

Return repr(self).

__str__() str

Return str(self).

__iadd__(value: Any) Collection[Any]
__add__(other: Collection[Any]) Collection[Any]
__radd__(other: Collection[Any]) Collection[Any]
__isub__(other: Collection[Any]) Collection[Any]
__sub__(other: Any) Collection[Any]
__rsub__(other: Collection[Any]) Collection[Any]
__imul__(times: int) Collection[Any]
__abstractmethods__ = frozenset({})
__annotations__ = {'_options': 'Optional[Dict[str, Any]]', 'root': 'Collection[Any]'}
__dict__ = mappingproxy({'__module__': 'fagus.fagus', '__annotations__': {'root': 'Collection[Any]', '_options': 'Optional[Dict[str, Any]]'}, '__doc__': 'Fagus is a wrapper-class for complex, nested objects of dicts and lists in Python\n\n    Fagus can be used as an object by instantiating it, but it\'s also possible to use all methods statically without\n    even an object, so that ``a = {}; Fagus.set(a, "top med", 1)`` and ``a = Fagus({}); a.set(1, "top med")`` do the\n    same.\n\n    The root node is always modified directly. If you don\'t want to change the root node, all the functions where it\n    makes sense support to rather modify a copy, and return that modified copy using the copy-parameter.\n\n    **FagusOptions**:\n    Several parameters used in functions in Fagus work as options so that you don\'t have to specify them each time you\n    run a function. In the docstrings, these options are marked with a \\*, e.g. the fagus parameter is an option.\n    Options can be specified at three levels with increasing precedence: at class-level (``Fagus.fagus = True``), at\n    object-level (``a = Fagus(), a.fagus = True``) and in each function-call (``a.get("b", fagus=True)``). If you\n    generally want to change an option, change it at class-level - all objects in that file will inherit this option.\n    If you want to change the option specifically for one object, change the option at object-level. If you only want\n    to change the option for one single run of a function, put it as a function-parameter. More thorough examples of\n    options can be found in README.md.\n    ', '__init__': <function Fagus.__init__>, 'get': <function Fagus.get>, 'iter': <function Fagus.iter>, 'filter': <function Fagus.filter>, 'split': <function Fagus.split>, '_split_r': <staticmethod(<function Fagus._split_r>)>, 'set': <function Fagus.set>, 'append': <function Fagus.append>, 'extend': <function Fagus.extend>, 'insert': <function Fagus.insert>, 'add': <function Fagus.add>, 'update': <function Fagus.update>, '_build_node': <function Fagus._build_node>, '_put_value': <staticmethod(<function Fagus._put_value>)>, 'setdefault': <function Fagus.setdefault>, 'mod': <function Fagus.mod>, 'mod_all': <function Fagus.mod_all>, 'serialize': <function Fagus.serialize>, '_serialize_r': <staticmethod(<function Fagus._serialize_r>)>, '_serializable_value': <staticmethod(<function Fagus._serializable_value>)>, 'merge': <function Fagus.merge>, 'pop': <function Fagus.pop>, 'popitem': <function Fagus.popitem>, 'discard': <function Fagus.discard>, 'remove': <function Fagus.remove>, 'keys': <function Fagus.keys>, 'values': <function Fagus.values>, 'items': <function Fagus.items>, 'clear': <function Fagus.clear>, 'contains': <function Fagus.contains>, 'count': <function Fagus.count>, 'index': <function Fagus.index>, 'isdisjoint': <function Fagus.isdisjoint>, 'child': <function Fagus.child>, 'reversed': <function Fagus.reversed>, 'reverse': <function Fagus.reverse>, 'copy': <function Fagus.copy>, 'options': <function Fagus.options>, '_opt': <function Fagus._opt>, '_ensure_mutable_node': <staticmethod(<function Fagus._ensure_mutable_node>)>, '_get_mutable_node': <function Fagus._get_mutable_node>, '_mutable_node_type': <staticmethod(<function Fagus._mutable_node_type>)>, '_node_type': <staticmethod(<function Fagus._node_type>)>, '_hash': <function Fagus._hash>, '__copy__': <function Fagus.__copy__>, '__call__': <function Fagus.__call__>, '__getattr__': <function Fagus.__getattr__>, '__getitem__': <function Fagus.__getitem__>, '__setattr__': <function Fagus.__setattr__>, '__setitem__': <function Fagus.__setitem__>, '__delattr__': <function Fagus.__delattr__>, '__delitem__': <function Fagus.__delitem__>, '__iter__': <function Fagus.__iter__>, '__hash__': <function Fagus.__hash__>, '__eq__': <function Fagus.__eq__>, '__ne__': <function Fagus.__ne__>, '__lt__': <function Fagus.__lt__>, '__le__': <function Fagus.__le__>, '__gt__': <function Fagus.__gt__>, '__ge__': <function Fagus.__ge__>, '__contains__': <function Fagus.__contains__>, '__len__': <function Fagus.__len__>, '__bool__': <function Fagus.__bool__>, '__repr__': <function Fagus.__repr__>, '__str__': <function Fagus.__str__>, '__iadd__': <function Fagus.__iadd__>, '__add__': <function Fagus.__add__>, '__radd__': <function Fagus.__radd__>, '__isub__': <function Fagus.__isub__>, '__sub__': <function Fagus.__sub__>, '__rsub__': <function Fagus.__rsub__>, '__imul__': <function Fagus.__imul__>, '__mul__': <function Fagus.__mul__>, '__rmul__': <function Fagus.__rmul__>, '__reversed__': <function Fagus.__reversed__>, '__reduce__': <function Fagus.__reduce__>, '__reduce_ex__': <function Fagus.__reduce_ex__>, '__dict__': <attribute '__dict__' of 'Fagus' objects>, '__weakref__': <attribute '__weakref__' of 'Fagus' objects>, '__abstractmethods__': frozenset(), '_abc_impl': <_abc._abc_data object>})
__module__ = 'fagus.fagus'
__mul__(times: int) Union[Tuple[Any], List[Any]]
__weakref__

list of weak references to the object (if defined)

__rmul__(times: int) Union[Tuple[Any], List[Any]]
__reversed__() Iterator[Any]
__reduce__() Union[str, Tuple[Any, ...]]

Helper for pickle.

__reduce_ex__(protocol: Any) Union[str, Tuple[Any, ...]]

Helper for pickle.

class fagus.Fil(*filter_args: Any, inexclude: str = '', str_as_re: bool = False)

Bases: KFil

TFilter - what matches this filter will actually be visible in the result. See README

__module__ = 'fagus.filters'
class fagus.CFil(*filter_args: Any, inexclude: str = '', str_as_re: bool = False, invert: bool = False)

Bases: KFil

CFil - can be used to select nodes based on values that shall not appear in the result. See README

__init__(*filter_args: Any, inexclude: str = '', str_as_re: bool = False, invert: bool = False) None

Initializes KeyFilter and verifies the arguments passed to it

Parameters:
  • *filter_args – Each argument filters one key in the tree, the last argument filters the leaf-value. You can put a list of values to match different values in the same filter. In this list, you can also specify subfilters to match different grains differently.

  • inexclude – In some cases it’s easier to specify that a filter shall match everything except b, rather than match a. ~ can be used to specify for each argument if the filter shall include it (+) or exclude it (-). Valid example: “++-+”. If this parameter isn’t specified, all args will be treated as (+).

  • str_as_re – If this is set to True, it will be evaluated for all str’s if they’d match differently as a regex, and in the latter case match these strings as regex patterns. E.g. re.match(“a.*”, b) will match differently than “a.*” == b. In this case, “a.*” will be used as a regex-pattern. However re.match(“abc”, b) will give the same result as “abc” == b, so here “abc” == b will be used.

Raises:

TypeError – if the filters are not stacked correctly, or stacked in a way that doesn’t make sense

match_node(node: Collection[Any], index: int = 0) bool

Recursive function to completely verify a node and its subnodes in CFil

Parameters:
  • node – node to check

  • index – index in filter to check (filter is self)

Returns:

bool whether the filter matched

__annotations__ = {}
__module__ = 'fagus.filters'
class fagus.VFil(*filter_args: Any, inexclude: str = '', invert: bool = False)

Bases: FilBase

ValueFilter - This special type of filter can be used to inspect the entire node

It can be used to e.g. select all the nodes that contain at least 10 elements. See README for an example

__init__(*filter_args: Any, inexclude: str = '', invert: bool = False) None
Parameters:
  • *filter_args – Each argument filters one key in the tree, the last argument filters the leaf-value. You can put a list of values to match different values in the same filter. In this list, you can also specify subfilters to match different grains differently.

  • inexclude – In some cases it’s easier to specify that a filter shall match everything except b, rather than match a. ~ can be used to specify for each argument if the filter shall include it (+) or exclude it (-). Valid example: “++-+”. If this parameter isn’t specified, all args will be treated as (+).

  • invert – Invert this whole filter to match if it doesn’t match. E.g. if you want to select all the nodes that don’t have a certain property.

match_node(node: Collection[Any], _: Optional[Any] = None) bool

Verify that a node matches ValueFilter

Parameters:
  • node – node to check

  • _ – this argument is ignored

Returns:

bool whether the filter matched

__annotations__ = {}
__module__ = 'fagus.filters'

Submodules