Skip to content

Commit

Permalink
Added as_pure_dictionary method for proper pickling and unpickling of…
Browse files Browse the repository at this point in the history
… recursive UltraDict instances (#25)
  • Loading branch information
ilbuonmarcio authored Sep 17, 2024
1 parent 4508f4a commit 0dec0b0
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
13 changes: 13 additions & 0 deletions UltraDict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,19 @@ def unlink_by_name(name, ignore_errors=False):
raise e
return False

@classmethod
def as_pure_dictionary(cls, to_convert=None):
if to_convert is None:
to_convert = cls

if isinstance(to_convert, UltraDict):
res = dict(to_convert)
for key in res.keys():
res[key] = cls.as_pure_dictionary(res[key])

return res

return to_convert


# Saved as a reference
Expand Down
52 changes: 52 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,58 @@ def test_example_recover_from_stale_lock(self):
self.assertEqual(ret.stdout.splitlines()[-1], b"Counter: 100 == 100", self.exec_show_output(ret))


def test_export_as_pure_dict(self):
ultra = UltraDict(
{
"1": "hello",
"2": 5,
"3": {
"1": 1,
"2": {
"1": True,
"2": None,
"3": [1, 2, 3]
},
"3": [4, 5, 6, {"7": 8}]
}
},
recurse=True
)

ultra2 = UltraDict(
{
"1": "hello",
"2": 5,
"3": {
"1": 1,
"2": {
"1": True,
"2": None,
"3": [1, 2, 3]
},
"3": [4, 5, 6, {"7": 8}]
}
},
recurse=False
)


def assert_pure_dict(elem):
self.assertNotIsInstance(elem, UltraDict)

if isinstance(elem, dict):
for key in elem.keys():
assert_pure_dict(elem[key])


with self.assertRaises(AssertionError):
assert_pure_dict(ultra)
assert_pure_dict(ultra2)

assert_pure_dict(ultra.as_pure_dictionary())
assert_pure_dict(ultra2.as_pure_dictionary())


if __name__ == '__main__':
if len(sys.argv) > 1:
for i in range(0, len(sys.argv)):
Expand Down

0 comments on commit 0dec0b0

Please sign in to comment.