Skip to content

Commit

Permalink
Dict: implement the __contains__ method (#5328)
Browse files Browse the repository at this point in the history
This now allows to do the following:

    'some_key' in Dict({'value'})

and is guaranteed to return a boolean, instead of raising a `KeyError`
if the key doesn't exist, which was the previous behavior.
  • Loading branch information
sphuber authored Jan 26, 2022
1 parent eaeb8e7 commit af3bb3d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion aiida/orm/nodes/data/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,12 @@ def __eq__(self, other):
return self.get_dict() == other.get_dict()
return self.get_dict() == other

def __contains__(self, key: str) -> bool:
"""Return whether the node contains a key."""
return key in self.attributes

def set_dict(self, dictionary):
""" Replace the current dictionary with another one.
"""Replace the current dictionary with another one.
:param dictionary: dictionary to set
"""
Expand Down
12 changes: 12 additions & 0 deletions tests/orm/nodes/data/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ def test_set_item(dictionary):
assert node['value'] == 3


@pytest.mark.usefixtures('clear_database_before_test')
@pytest.mark.parametrize('key, expected', (('value', True), ('non-existing', False)))
def test_contains(dictionary, key, expected):
"""Test the ``__contains__`` implementation."""
node = Dict(dictionary)
assert (key in dictionary) is expected
assert (key in node) is expected

node.store()
assert (key in node) is expected


@pytest.mark.usefixtures('clear_database_before_test')
def test_correct_raises(dictionary):
"""Test that the methods for accessing the item raise the correct error.
Expand Down

0 comments on commit af3bb3d

Please sign in to comment.