From a924829821367b9d3d008f2fe68f54f714f92f43 Mon Sep 17 00:00:00 2001 From: Dmitry Vasilev Date: Fri, 18 Jan 2019 01:44:02 +0500 Subject: [PATCH] Add nested_update.in_place argument (#13) * Add nested_update.in_place argument * Update README.rst and tests --- README.rst | 8 ++++---- nested_lookup/lookup_api.py | 7 ++++--- test_lookup_api.py | 13 +++++++++++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/README.rst b/README.rst index 87af024..ac112e5 100644 --- a/README.rst +++ b/README.rst @@ -14,11 +14,11 @@ A document in this case is a a mixture of Python dictionary and list objects typ Returns a `list` of matching values. *nested_update:* - Given a document, find all occurances of the given key and update the value. - Returns a copy of the document. + Given a document, find all occurences of the given key and update the value + By default, returns a copy of the document. To mutate the original one instead - please specify the `in_place=True` argument. *nested_delete:* - Given a document, find all occurances of the given key and delete it. + Given a document, find all occurrences of the given key and delete it. Returns a copy of the document. *get_all_keys:* @@ -178,7 +178,7 @@ To get a list of every nested key in a document, run this: print(keys) .. code-block:: python - + ['name', 'email_address', 'other', 'secondary_email', 'EMAIL_RECOVERY', 'email_address'] To get the number of occurrence of the given key/value diff --git a/nested_lookup/lookup_api.py b/nested_lookup/lookup_api.py index f986ca7..221ef31 100644 --- a/nested_lookup/lookup_api.py +++ b/nested_lookup/lookup_api.py @@ -28,9 +28,10 @@ def _nested_delete(document, key): return document -def nested_update(document, key, value): - duplicate = copy.deepcopy(document) - return _nested_update(document=duplicate, key=key, value=value) +def nested_update(document, key, value, in_place=False): + if not in_place: + document = copy.deepcopy(document) + return _nested_update(document=document, key=key, value=value) def _nested_update(document, key, value): diff --git a/test_lookup_api.py b/test_lookup_api.py index 4b96781..f7d6a60 100644 --- a/test_lookup_api.py +++ b/test_lookup_api.py @@ -103,6 +103,19 @@ class TestNestedUpdate(BaseLookUpApi): result, nested_update(self.sample_data1, 'build_version', 'Test1') ) + def test_in_place(self): + result = { + "build_version": "Test1", + "os_details": { + "product_version": '10.13.6', + "build_version": 'Test1' + }, + "name": 'Test', + "date": 'YYYY-MM-DD HH:MM:SS' + } + nested_update(self.sample_data1, 'build_version', 'Test1', in_place=True) + self.assertEqual(result, self.sample_data1) + def test_sample_data2(self): result = { "hardware_details": {