bt2: field.py: add index check in `selected_option_index` setter of `_VariantField`
[babeltrace.git] / src / bindings / python / bt2 / bt2 / field.py
index 512271bd95c9a055f6b6108be2035cb5344f043a..56f94f0fb33b8fd4ed33db31059e5849742c8420 100644 (file)
@@ -59,7 +59,7 @@ class _Field(object._UniqueObject):
         return self._spec_eq(other)
 
     @property
-    def field_class(self):
+    def cls(self):
         field_class_ptr = native_bt.field_borrow_class_const(self._ptr)
         assert field_class_ptr is not None
         return bt2_field_class._create_field_class_from_ptr_and_get_ref(field_class_ptr)
@@ -96,7 +96,7 @@ class _BitArrayField(_Field):
         return str(self.value_as_integer)
 
     def __len__(self):
-        return self.field_class.length
+        return self.cls.length
 
 
 @functools.total_ordering
@@ -141,7 +141,7 @@ class _NumericField(_Field):
     def _spec_eq(self, other):
         try:
             return self._value == self._extract_value(other)
-        except:
+        except Exception:
             return False
 
     def __rmod__(self, other):
@@ -393,7 +393,7 @@ class _StringField(_Field):
     def _spec_eq(self, other):
         try:
             return self._value == self._value_to_str(other)
-        except:
+        except Exception:
             return False
 
     def __lt__(self, other):
@@ -440,7 +440,7 @@ class _StructureField(_ContainerField, collections.abc.MutableMapping):
     _NAME = 'Structure'
 
     def _count(self):
-        return len(self.field_class)
+        return len(self.cls)
 
     def __setitem__(self, key, value):
         # raises if key is somehow invalid
@@ -452,7 +452,7 @@ class _StructureField(_ContainerField, collections.abc.MutableMapping):
 
     def __iter__(self):
         # same name iterator
-        return iter(self.field_class)
+        return iter(self.cls)
 
     def _spec_eq(self, other):
         if not isinstance(other, collections.abc.Mapping):
@@ -559,12 +559,18 @@ class _OptionField(_Field):
 class _VariantField(_ContainerField, _Field):
     _NAME = 'Variant'
 
+    def _count(self):
+        return len(self.cls)
+
     @property
     def selected_option_index(self):
         return native_bt.field_variant_get_selected_option_field_index(self._ptr)
 
     @selected_option_index.setter
     def selected_option_index(self, index):
+        if index < 0 or index >= len(self):
+            raise IndexError('{} field object index is out of range'.format(self._NAME))
+
         native_bt.field_variant_select_option_field_by_index(self._ptr, index)
 
     @property
This page took 0.025336 seconds and 4 git commands to generate.