diff --git a/src/hooked_containers/mapping.py b/src/hooked_containers/mapping.py index 8fd0995..56a708e 100644 --- a/src/hooked_containers/mapping.py +++ b/src/hooked_containers/mapping.py @@ -40,7 +40,9 @@ class HookedMapping(HookedContainer[T], MutableMapping[T, MutableNesting[T]]): # HookedContainer methods def __getitem__(self, key: T) -> MutableNesting[T]: - value = self._data.get(key, {}) + if key not in self._data: + self.insert(key, {}) + value = self._data[key] match value: case HookedMapping(_data=seq): return type(self)(seq, hook=self.hook, path=self.new_path(key)) @@ -50,6 +52,9 @@ class HookedMapping(HookedContainer[T], MutableMapping[T, MutableNesting[T]]): return item def __setitem__(self, key: T, value: MutableNesting[T]) -> None: + if key not in self._data: + self.insert(key, value) + return self._data[key] = value if self.hook: self.hook(e.SetItemEvent(index=key, item=value, path=self.new_path(key)))