Search code examples
pythonvariablesupdatesstoreself

Python: Storing value of self Variable


I've got a problem with storing my Variable self.data_counter in an other variable like prev_counter_data. I simply can't store the current value - the variable i assign self.data_counter to has always the exact same values somehow.

class SimpleSwitch(app_manager.RyuApp):

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch, self).__init__(*args, **kwargs)
        self.data_counter = {}
        self.monitor_thread = hub.spawn(self._monitor)

    def _monitor(self):
        timer = 0
        prev_data_counter = self.data_counter
        while True:
            hub.sleep(5)
            timer = timer + 5
            # assign current values to self.data_counter in func()
            func()
            # compare current values to previous values

            if (timer%60) == 0:
                prev_data_counter = self.data_counter

Any idea where the flaw in my thinking is? Why is prev_data_counter always equal to self.data_counter?

The Dictionary self.data_countercontains information like [(id, port):traffic]. I can assign values via self.data_counter[id][port] = traffic.


Solution

  • When you do self.prev_data_counter = self.data_counter we are saying they are the same object.

    Try:

    self.prev_data_counter = copy.copy(self.data_counter)

    And add the copy package: import copy

    See also: https://docs.python.org/2/library/copy.html