aboutsummaryrefslogtreecommitdiffstats
path: root/snips_inference_agl/common/dict_utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'snips_inference_agl/common/dict_utils.py')
-rw-r--r--snips_inference_agl/common/dict_utils.py36
1 files changed, 36 insertions, 0 deletions
diff --git a/snips_inference_agl/common/dict_utils.py b/snips_inference_agl/common/dict_utils.py
new file mode 100644
index 0000000..a70b217
--- /dev/null
+++ b/snips_inference_agl/common/dict_utils.py
@@ -0,0 +1,36 @@
+from collections import OrderedDict
+
+
+class LimitedSizeDict(OrderedDict):
+ def __init__(self, *args, **kwds):
+ if "size_limit" not in kwds:
+ raise ValueError("'size_limit' must be passed as a keyword "
+ "argument")
+ self.size_limit = kwds.pop("size_limit")
+ if len(args) > 1:
+ raise TypeError('expected at most 1 arguments, got %d' % len(args))
+ if len(args) == 1 and len(args[0]) + len(kwds) > self.size_limit:
+ raise ValueError("Tried to initialize LimitedSizedDict with more "
+ "value than permitted with 'limit_size'")
+ super(LimitedSizeDict, self).__init__(*args, **kwds)
+
+ def __setitem__(self, key, value, dict_setitem=OrderedDict.__setitem__):
+ dict_setitem(self, key, value)
+ self._check_size_limit()
+
+ def _check_size_limit(self):
+ if self.size_limit is not None:
+ while len(self) > self.size_limit:
+ self.popitem(last=False)
+
+ def __eq__(self, other):
+ if self.size_limit != other.size_limit:
+ return False
+ return super(LimitedSizeDict, self).__eq__(other)
+
+
+class UnupdatableDict(dict):
+ def __setitem__(self, key, value):
+ if key in self:
+ raise KeyError("Can't update key '%s'" % key)
+ super(UnupdatableDict, self).__setitem__(key, value)