Skip to content

Commit

Permalink
ORM: Implement the Dict.get method (#6200)
Browse files Browse the repository at this point in the history
This makes the behavior of `Dict` identical to that of a plain `dict`
with respect to this method. The `Dict` class inherited the `get` method
from the `Entity` base class, but that has a completely different
purpose that is not of interest for users of the `Dict` class.
  • Loading branch information
sphuber authored Dec 1, 2023
1 parent ca8bbc6 commit 184fcd1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions aiida/orm/nodes/data/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
# For further information please visit http://www.aiida.net #
###########################################################################
"""`Data` sub class to represent a dictionary."""
from __future__ import annotations

import copy
import typing as t

from aiida.common import exceptions

Expand Down Expand Up @@ -79,6 +82,15 @@ def __contains__(self, key: str) -> bool:
"""Return whether the node contains a key."""
return key in self.base.attributes

def get(self, key: str, default: t.Any | None = None, /): # type: ignore[override] # pylint: disable=arguments-differ
"""Return the value for key if key is in the dictionary, else default.
:param key: The key whose value to return.
:param default: Optional default to return in case the key does not exist.
:returns: The value if the key exists, otherwise the ``default``.
"""
return self.base.attributes.get(key, default)

def set_dict(self, dictionary):
"""Replace the current dictionary with another one.
Expand Down
9 changes: 9 additions & 0 deletions tests/orm/nodes/data/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ def test_dict_property(dictionary):
assert node.dict.nested == dictionary['nested']


def test_get(dictionary):
"""Test the ``get`` method."""
node = Dict(dictionary)
assert node.get('invalid') is None
assert node.get('invalid', 'default') == 'default'
assert node.get('value') == dictionary['value']
assert node.get('nested') == dictionary['nested']


def test_get_item(dictionary):
"""Test the ``__getitem__`` method."""
node = Dict(dictionary)
Expand Down

0 comments on commit 184fcd1

Please sign in to comment.