'modifying contents of a copied variable imported from another file changes original variable contents
I have a constants file from which i import a variable that has nested dictionaries and lists in it. When a certain API is called i alter some variable value while iterating over the contents
import deep_nested_dict from another_file
class MyViewSet(viewsets.ModelViewSet):
def list(self):
for top_lvl_key in deep_nested_dict['results']:
list_of_dicts = deep_nested_dict['results'][top_lvl_key]:
for dictitems in list_of_dicts:
if "somestr" in dictitems['variable']:
dictitems['variable'] = dictitems['variable'].replace("somestr", "anotherstr")
When the API is called for the first time it works fine but subsequent calls fail because "somestr" is already replace the first time and that keeps living in the ram
the current solution i have is to make a deepcopy of the original value but somehow feel this is more of a fix than a solution
import deep_nested_dict from another_file as og_deep_nested_dict
class MyViewSet(viewsets.ModelViewSet):
def list(self):
deep_nested_dict = copy.deepcopy(og_deep_nested_dict)
for top_lvl_key in deep_nested_dict['results']:
list_of_dicts = deep_nested_dict['results'][top_lvl_key]:
for dictitems in list_of_dicts:
if "somestr" in dictitems['variable']:
dictitems['variable'] = dictitems['variable'].replace("somestr", "anotherstr")
another option i thought of which i am not a fan of is to import deep_nested_dict for every API call
what is the most appropriate way to resolve this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
