JaboSammy
JaboSammy

Reputation: 35

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.

Upvotes: 0

Views: 1116

Answers (2)

Jan Giacomelli
Jan Giacomelli

Reputation: 1339

Your data counter is dictionary. Dictionaries are mutable objects. When you asign self.data_counter to prev_data_counter you actually just save the reference to the same dictionary object. So when you update self.data_counter you update prev_data_counter too - they are referencing to the same object.

You need to create copy of your dictionary:

prev_data_counter = self.data_counter.copy()

Upvotes: 1

Carlos Galdino
Carlos Galdino

Reputation: 314

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

Upvotes: 2

Related Questions