Skip to content

Commit

Permalink
Prevent clearing dict instance when assigning value to itself. fabioc…
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo committed May 31, 2023
1 parent 18629ba commit 9800f21
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions benedict/dicts/base/base_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ def __setitem__(self, key, value):
is_dict_item = key in self._dict and isinstance(self._dict[key], dict)
is_dict_value = isinstance(value, dict)
if is_dict_item and is_dict_value:
if self._dict[key] is value:
# prevent clearing dict instance when assigning value to itself. fix #294
return
self._dict[key].clear()
self._dict[key].update(value)
return
Expand Down
20 changes: 20 additions & 0 deletions tests/github/test_issue_0294.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import unittest

from benedict import benedict


class github_issue_0294_test_case(unittest.TestCase):
"""
This class describes a github issue 0294 test case.
https://github.com/fabiocaccamo/python-benedict/issues/294
To run this specific test:
- Run python -m unittest tests.github.test_issue_0294
"""

def test_assigning_benedict_element_to_itself_clears_the_element(self):
d = benedict({"a": {"b": 1}})
d["a"] = d["a"]
self.assertEqual(d, {"a": {"b": 1}})
d.a = d.a
self.assertEqual(d, {"a": {"b": 1}})

0 comments on commit 9800f21

Please sign in to comment.