bt2: add `__hash__()` method on hashable fields
[babeltrace.git] / src / bindings / python / bt2 / bt2 / field.py
index 4f89d1e43a10ccedcf36c9eff846f9a1f6f09f0e..1e2ceac30efa0c6ab80cef0f5db7f84f6e6e2913 100644 (file)
@@ -180,6 +180,9 @@ class _NumericFieldConst(_FieldConst):
         except Exception:
             return False
 
+    def __hash__(self):
+        return hash(self._value)
+
     def __rmod__(self, other):
         return self._extract_value(other) % self._value
 
@@ -242,7 +245,10 @@ class _NumericFieldConst(_FieldConst):
 
 
 class _NumericField(_NumericFieldConst, _Field):
-    pass
+    def __hash__(self):
+        # Non const field are not hashable as their value may be modified
+        # without changing the underlying Python object.
+        raise TypeError('unhashable type: \'{}\''.format(self._NAME))
 
 
 class _IntegralFieldConst(_NumericFieldConst, numbers.Integral):
@@ -483,6 +489,9 @@ class _StringFieldConst(_FieldConst):
     def __bool__(self):
         return bool(self._value)
 
+    def __hash__(self):
+        return hash(self._value)
+
     def _repr(self):
         return repr(self._value)
 
@@ -513,6 +522,11 @@ class _StringField(_StringFieldConst, _Field):
         )
         return self
 
+    def __hash__(self):
+        # Non const field are not hashable as their value may be modified
+        # without changing the underlying Python object.
+        raise TypeError('unhashable type: \'{}\''.format(self._NAME))
+
 
 class _ContainerFieldConst(_FieldConst):
     def __bool__(self):
This page took 0.024302 seconds and 4 git commands to generate.