Coverage for kwave/utils/dotdictionary.py: 42%
21 statements
« prev ^ index » next coverage.py v7.7.1, created at 2025-03-24 12:06 -0700
« prev ^ index » next coverage.py v7.7.1, created at 2025-03-24 12:06 -0700
1from typing import Any
4class dotdict(dict):
5 """
6 A dictionary supporting dot notation.
8 This class extends the built-in `dict` type by adding support for accessing
9 items using dot notation (e.g. `dotdict.a.b.c`) instead of square bracket
10 notation (e.g. `dotdict['a']['b']['c']`). The class also provides a
11 `lookup` method for looking up a value in a nested dictionary structure
12 using a dot-separated path (e.g. "a.b.c").
14 Examples:
15 >>> d = dotdict({'a': {'b': {'c': 1}}})
16 >>> d.a.b.c
17 1
18 >>> d.lookup('a.b.c')
19 1
21 """
23 __getattr__ = dict.get
24 __setattr__ = dict.__setitem__
25 __delattr__ = dict.__delitem__
27 def __init__(self, *args: Any, **kwargs: Any) -> None:
28 super().__init__(*args, **kwargs)
29 for k, v in self.items():
30 if isinstance(v, dict): 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true
31 self[k] = dotdict(v)
33 def lookup(self, dotkey: str) -> Any:
34 """
35 Look up a value in a nested dictionary structure using a dot-separated path.
37 Args:
38 dotkey: A dot-separated path to the value, e.g. "a.b.c".
40 Returns:
41 The value at the specified path.
43 Raises:
44 KeyError: If the specified path does not exist in the dictionary.
46 """
47 path = list(reversed(dotkey.split(".")))
48 v = self
49 while path:
50 key = path.pop()
51 if isinstance(v, dict):
52 v = v[key]
53 elif isinstance(v, list):
54 v = v[int(key)]
55 else:
56 raise KeyError(key)
57 return v