Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems with version control for dictionaries inside a python class

I’m doing something wrong in the code below. I have a method (update_dictonary) that changes a value or values in a dictionary based on what is specificed in a tuple (new_points).

Before I update the dictionary, I want to save that version in a list (history) in order to be able to access previous versions. However, my attempt below updates all dictionaries in history to be like the latest version.

I can’t figure out what I’m doing wrong here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test_dict = {'var0':{'var1':{'cond1':1,
                            'cond2':2,
                            'cond3':3}
                    }
            }

class version_control:
    
    def __init__ (self, dictionary):
        self.po = dictionary
        self.history = list()
        self.version = 0

    def update_dictionary(self, var0, var1, new_points):
            po_ = self.po
            self.history.append(po_)

            for i in new_points:
                 self.po[var0][var1][i[0]] = i[1]

            self.version += 1
    
    def get_history(self, ver):
        return self.history[ver]


a = version_control(test_dict)

new_points = [('cond1', 2),
             ('cond2', 0)]

a.update_dictionary('var0', 'var1', new_points)

new_points = [('cond3', -99),
             ('cond2', 1)]

a.update_dictionary('var0', 'var1', new_points)

print(a.get_history(0))
print(a.get_history(1))

>Solution :

Try this

from copy import deepcopy

...
def update_dictionary(self, var0, var1, new_points):
    po_ = deepcopy(self.po)
    self.history.append(po_)

    for i in new_points:
        self.po[var0][var1][i[0]] = i[1]

    self.version += 1
...

The problem here is that when you assign po_= self.po you expect po_ to a variable but actually, you just make a shallow copy of your dictionary. This means if you update the self.po then op_ will automatically update.


To solve this problem using deepcopy from the copy module(Built-in). It will create a new variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading