Repository: SINTEF/dlite (language: python)

Issue:
Ensure that collection labels are unique
Make it an error if one adds an instance with an already existing label.

In the Python interface, consider to add an option `force=False` to replace a possible existing label. Remember to decref the replaced instance.



Discussion / hints:

Fix patch:
diff --git a/bindings/python/dlite-collection-python.i b/bindings/python/dlite-collection-python.i
index c45f62612..85740a1cf 100644
--- a/bindings/python/dlite-collection-python.i
+++ b/bindings/python/dlite-collection-python.i
@@ -146,8 +146,12 @@ class Collection(Instance):
     def __contains__(self, label):
         return self.has(label)
 
-    def add(self, label, inst):
-        """Add `inst` to collection with given label."""
+    def add(self, label, inst, force=False):
+        """Add `inst` to collection with given label.
+        If `force` is true, a possible existing instance will be replaced.
+        """
+        if force and self.has(label):
+            self.remove(label)
         _collection_add(self._coll, label, inst)
 
     def remove(self, label):


Test patch:
diff --git a/bindings/python/tests/test_collection.py b/bindings/python/tests/test_collection.py
index 24b43fdb4..762452e1b 100755
--- a/bindings/python/tests/test_collection.py
+++ b/bindings/python/tests/test_collection.py
@@ -80,9 +80,15 @@
 assert inst1b == inst1
 assert inst1b != inst2
 
+# Cannot add an instance with an existing label
+try:
+    coll.add('inst1', inst2)
+except dlite.DLiteError:
+    pass
+else:
+    raise RuntimeError('should not be able to replace an existing instance')
 
-#
-
+coll.add('inst1', inst2, force=True)  # forced replacement
 
 s = str(coll)
 print(coll)