Skip to content

Commit

Permalink
Fix wrong raise from dict nodes
Browse files Browse the repository at this point in the history
When accessing an attribute as a dict (`dictnode['key']`), the error
raised was an AttributeError instead of a KeyError, which is rather
unusual. This has been fixed and a test that checks the correct error
raise has been added.

Cherry-pick: 87d7a60
  • Loading branch information
ramirezfranciscof committed Dec 4, 2020
1 parent 8058a97 commit a5717e8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion aiida/orm/nodes/data/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ def __init__(self, **kwargs):
self.set_dict(dictionary)

def __getitem__(self, key):
return self.get_attribute(key)
try:
return self.get_attribute(key)
except AttributeError as exc:
raise KeyError from exc

def __setitem__(self, key, value):
self.set_attribute(key, value)
Expand Down
12 changes: 12 additions & 0 deletions tests/orm/data/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,15 @@ def test_set_item(self):
self.assertEqual(self.node['value'], 2)
self.node.dict.value = 3
self.assertEqual(self.node['value'], 3)

def test_correct_raises(self):
"""Test that the methods for accessing the item raise the correct error.
* `dictnode['inexistent']` should raise KeyError
* `dictnode.dict.inexistent` should raise AttributeError
"""
with self.assertRaises(KeyError):
_ = self.node['inexistent_key']

with self.assertRaises(AttributeError):
_ = self.node.dict.inexistent_key

0 comments on commit a5717e8

Please sign in to comment.