Low-level Utilities

import kloch
class kloch.MergeableDict

Bases: dict

A dict that can be deep-merged with another dict.

The merging algorithm is defined in deepmerge_dicts.

You can define the merging granularity on a per-key basis by adding token prefix to your keys.

Available tokens are found in MergeableDict.tokens.

Example

from kloch import MergeableDict
dict_1 = MergeableDict({"+=config": {"cache": True, "level": 3, "port": "A46"}})
dict_2 = MergeableDict({"+=config": {"cache": False, "-=level": 3}})
print(dict_1 + dict_2)

results:

{'+=config': {'port': 'A46', 'cache': False}}
__add__(other: T) T

Merge the 2 dict structure together with other merged over self.

The returned class type is of the left member of the + operation.

Returns:

new instance with deepcopied structure.

get(key, default=None, ignore_tokens: bool = False)
Parameters:
  • key – key’s value to retrieve

  • default – value to return if key is not in the dict

  • ignore_tokens – if True, both key and self are used with a resolved variant (without tokens). For example .get("config",ignore_tokens=True) would still return {...} if self=={"+=config":{...}}.

classmethod get_merge_rule(key: str) MergeRule

Extract the MergeRule for the given key based on its potential token.

classmethod resolve_key_tokens(key: str) str

Ensure the given key has all potential tokens removed.

resolved() Dict

Get the dict structure with all tokens resolved.

Without tokens, the returned object become a regular dict instance.

Returns:

deepcopied dict structure.

class tokens

Bases: object

append = '+='
ifnotexists = '!='
override = '=='
remove = '-='
class kloch.MergeRule(value)

Bases: IntEnum

Define how 2 python objects should be merged together.

append = 2
ifnotexists = 4
override = 1
remove = 3
kloch.refacto_dict(src_dict: Dict, callback: Callable[[Any, Any], Tuple[Any, Any]], recursive=True) Dict

Iterate through all key/value pairs of the given dict and execute the given callback at each step which return a new key/value pair for the output dict.

Parameters:
  • src_dict – dict obejct ot iterate

  • callback – Callable expecting 2args: key, value and should return a tuple of new_key, new_value

  • recursive – True to recursively process child dict

Returns:

a new dict instance

kloch.deepmerge_dicts(over_content: Dict[str, Any], base_content: Dict, merge_rule_callback: Callable[[str], MergeRule] | None = None, key_resolve_callback: Callable[[str], str] | None = None) Dict[str, Any]

Recursively merge the 2 given dict “over one another”.

Intended to work best with dict having the same key/value structure.

The merging rules are defined by the given callbacks. If no callback is provided the default rule is to override.

The following object types supports the append rule:

  • list: with a .extend() behavior

  • dict: deepmerged recursively

For any other type, the over’s value override the base’s value.