Module attrbox.fn

Generally useful functions.

Global variables

var AnyList

Generic list.

var AnyDict

Generic dict.

var OnlyReadDict

dict that will only be read.

var AnyListDict

Generic list or dict.

var AnyIndex

Index into a list or dict.

Functions

def get_path(src: SupportsItem, path: Union[str, int, Sequence[Union[str, int]]], default: Optional[Any] = None) ‑> Any

Get the value indicated by path or return default if it is not found.

Args

src : SupportsItem
typically a list or a dict
path : AnyIndex
path to the value
default : Any, optional
value to return if path is not found. Defaults to None.

Returns

Any
path value or default if it is not found.

Examples

>>> get_path({'a': 1}, 'a')
1
>>> get_path({'a': [1, {'b': 2}]}, ['a', 1, 'b'])
2
def set_path(dest: Union[List[Any], Dict[Any, Any]], path: Union[str, int, Sequence[Union[str, int]]], value: Any, cls_dict: Type[Dict[Any, Any]] = builtins.dict, cls_list: Type[List[Any]] = builtins.list) ‑> Union[List[Any], Dict[Any, Any]]

Set a deeply nested value.

Args

dest : Box
a list or dict
path : BoxIndex
index or Sequence into dest
value : Any
the value to set
cls_dict : Type[dict], optional
Constructor for Mapping objects. Defaults to dict.
cls_list : Type[list], optional
Constructor for List objects. Defaults to list.

Returns

Box
dest modified according to the path. New dict and list objects will be created if they do not exist.

Examples

>>> item = {'a': [{'b': {'c': 3}}]}
>>> set_path(item, ['a', 0, 'b', 'c'], 4)
{'a': [{'b': {'c': 4}}]}
>>> set_path(item, ['a', 1, 'd'], 5)
{'a': [{'b': {'c': 4}}, {'d': 5}]}
def dict_merge(dest: Dict[Any, Any], *sources: Mapping[Any, Any], cls_dict: Type[Dict[Any, Any]] = builtins.dict) ‑> Dict[Any, Any]

Generic recursive merge for dict-like objects.

NOTE: Every nested dict will pass through cls_dict.

Args

dest : AnyDict
dict into which sources are merged
*sources : OnlyReadDict
dicts to merge
cls_dict : Type[AnyDict], optional
constructor for default dict. Defaults to dict.

Returns

AnyDict
dest now with merged values

Examples

>>> a = {"b": {"c": 1}, "d": 2}
>>> b = {"b": {"c": 2, "e": 3}, "d": 2}
>>> c = {"d": {"e": 5}}
>>> dict_merge(a, b, c)
{'b': {'c': 2, 'e': 3}, 'd': {'e': 5}}

Classes

class SupportsItem (*args, **kwargs)

Protocol for k in x, x[k], and x[k] = v.

Expand source code
@runtime_checkable
class SupportsItem(Protocol):  # pragma: no cover
    """Protocol for `k in x`, `x[k]`, and `x[k] = v`."""

    def __contains__(self, key: Any) -> bool:
        """Return `True` if `key` exists, `False` otherwise."""
        return False

    def __getitem__(self, key: Any) -> Any:
        """Return value of `key`."""

    def __setitem__(self, key: Any, value: Any) -> Optional[Any]:
        """Set `key` to `value`."""

Ancestors

  • typing.Protocol
  • typing.Generic