From dee954cf3ae31007786857a4e7e273a483ea85e4 Mon Sep 17 00:00:00 2001 From: Marnik Bercx Date: Mon, 20 Nov 2023 11:36:43 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=8C=20Return=20`frozendict`=20for=20st?= =?UTF-8?q?ored=20`Dict`=20nodes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aiida/orm/nodes/data/dict.py | 17 ++++++++++++++++- environment.yml | 1 + pyproject.toml | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/aiida/orm/nodes/data/dict.py b/aiida/orm/nodes/data/dict.py index e0a975f916..df7b3e4fce 100644 --- a/aiida/orm/nodes/data/dict.py +++ b/aiida/orm/nodes/data/dict.py @@ -10,6 +10,8 @@ """`Data` sub class to represent a dictionary.""" import copy +from frozendict import frozendict + from aiida.common import exceptions from .base import to_aiida_type @@ -62,15 +64,28 @@ def __init__(self, value=None, **kwargs): self.set_dict(dictionary) def __getitem__(self, key): + """Get the ``value`` of a key. + + If the node is not stored, the value is returned as is (if present). Once the node is stored, we check if the + value is a dictionary and if so, we return a ``frozendict`` instance to prevent modifications. This is to + prevent the user from modifying the dictionary in place, which would not be reflected in the database. + """ try: - return self.base.attributes.get(key) + value = self.base.attributes.get(key) except AttributeError as exc: raise KeyError from exc + if self.is_stored and isinstance(value, dict): + return frozendict(value) + + return value + def __setitem__(self, key, value): + """Set the ``value`` of a key.""" self.base.attributes.set(key, value) def __eq__(self, other): + """Compare if the current node is equal to another node or to a dictionary.""" if isinstance(other, Dict): return self.get_dict() == other.get_dict() return self.get_dict() == other diff --git a/environment.yml b/environment.yml index 7a8bd8a795..583873c264 100644 --- a/environment.yml +++ b/environment.yml @@ -14,6 +14,7 @@ dependencies: - click~=8.1 - disk-objectstore~=1.0 - docstring_parser +- frozendict~=2.3 - get-annotations~=0.1 - python-graphviz~=0.19 - ipython>=7 diff --git a/pyproject.toml b/pyproject.toml index 7f1fe1ca9a..c978480a93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,6 +33,7 @@ dependencies = [ "click~=8.1", "disk-objectstore~=1.0", "docstring-parser", + "frozendict~=2.3", "get-annotations~=0.1;python_version<'3.10'", "graphviz~=0.19", "ipython>=7",