Skip to content

Commit

Permalink
Merge pull request #248 from SINTEF/close-223-unique-labels-in-collec…
Browse files Browse the repository at this point in the history
…tion

Added option `force` to replace an existing instance in a collection.
  • Loading branch information
CasperWA authored Apr 26, 2022
2 parents aad022d + 3d055f6 commit 140f3ac
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
8 changes: 6 additions & 2 deletions bindings/python/dlite-collection-python.i
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
10 changes: 8 additions & 2 deletions bindings/python/tests/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 140f3ac

Please sign in to comment.