0

I tryed to read something on the topic but I cannot figure out a possible solution.

I have a dictionary of this type:

class flux(object):
    def __init__(self, count_flux=0, ip_c_dict=defaultdict(int), ip_s_dict=defaultdict(int), conn_dict=defaultdict(int)):
        self.count_flux = count_flux
        self.ip_c_dict = ip_c_dict if ip_c_dict is not None else {}
        self.ip_s_dict = ip_s_dict if ip_s_dict is not None else {}
        self.conn_dict = conn_dict if conn_dict is not None else {}

Every time I try to update the dictionary in this way:

dictionary[key].ip_c_dict[some_string]+=1

not only the dictionary of the current key is updated, but also all the others. And of course it happens with all the three dictionary in the class, ip_c_dict=defaultdict(int), ip_s_dict=defaultdict(int), conn_dict=defaultdict(int).

How can I fix it?

user2961420
  • 267
  • 1
  • 3
  • 8

1 Answers1

3

I said in that answer that you shouldn't put dicts in the default arguments, because then the dicts end up shared between all the instances. The defaultdict(int) in the default argument is evaluated only once (when the method is first created) and then all the times the method is called use that same dict as the default.

So put back ip_c_dict=None in the argument list, and below put

self.ip_c_dict = ip_c_dict if ip_c_dict is not None else defaultdict(int)

That way a new defaultdict(int) is created each time, if the ip_c_dict argument is None.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • 1
    Here's an explanation http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Leifingson Dec 13 '13 at 10:44