traceabledict module¶
TraceableDict - a new data structure inherits from Python dict, which allows the nested-key usages to be tracked.
- class genie.metaparser.util.traceabledict.TraceableDict(*args, **kwargs)¶
Bases:
dict
A subclass of Python dict that provides functionality of key usage tracking. The class allows to convert the common dict into TraceableDict data structure. All common Python dict key usage functionalities, for example:
dict[‘xx’]
dict.keys()
dict.items()
dict.values()
dict.get()
dict.copy()
dict.pop()
will be traced and saved into class variable -
tracer
for future access.- Parameters
key_map (
dict
) – dict to store the current key name and its key path, for example {‘aaa’: (‘a’, ‘aa’, ‘aaa’), ‘b’:(‘b’,)}dictname (
str
) – dictionary identity. choices of: ‘cl’, ‘xml’, ‘yang’, default is ‘cli’.
- Returns
a
TraceableDict
object
Examples
>>> from .util.traceabledict import TraceableDict >>> t = TraceableDict.convert(dict) >>> assert('TraceableDict'== t.__class__.__name__)
Class variables:
- tracer (
dict
): class variable to hold dictionary name and its key usage record, for example: {name1: {usage}, name2: {usage}}
- tracer = {}¶
- get(item)¶
tracing key usage when accessing dict: dict.get(‘xxx’)
note: only trace the leaf key to avoid fragment key confusion
- keys()¶
tracing key usage when accessing dict: dict.keys()
- values()¶
tracing key usage when accessing dict: dict.values()
- items()¶
tracing key usage when accessing dict: dict.items()
- copy()¶
tracing key usage when accessing dict: dict.copy()
note: copy itself won’t trace any key usage, but the copied dict will continuously be able to trace key usages.
- pop(item)¶
tracing key usage when accessing dict: dict.pop(‘xxx’)
- static convert(d, name, parent_key=None)¶
recursively convert Pyhton dict/nested dict into
TraceableDict
- Parameters
d (
dict
) – the dictionary needs to be convertedname (
str
) – TraceableDict nameparent_key (
list
) – the parent key path which leads to this dictionary. for example: for dic = {‘a’: {‘aa’: ‘xxx’}} parent_key will be None for dic, and will be [‘a’] for dic[‘a’]
- Returns
a
TraceableDict
obj
Example
>>> from .util.traceabledict import TraceableDict >>> d = {'a': {'aa': 'xxx'}} >>> t = TraceableDict.convert(d, 'my_traced_dict')