I ran into a weird problem today, here is some example code
from collections import defaultdict
class Counter:
hits = 0
visitors = set()
def addHit(self, ip):
self.hits += 1
self.visitors.add(ip)
d = defaultdict(Counter)
d['a'].addHit('1.1.1')
d['a'].addHit('2.2.2')
d['b'].addHit('3.3.3')
print d['a'].hits, d['a'].visitors
print d['b'].hits, d['b'].visitors
Expected Result:
2 set(['1.1.1', '2.2.2'])
1 set(['3.3.3'])
Actual Result:
2 set(['1.1.1', '3.3.3', '2.2.2'])
1 set(['1.1.1', '3.3.3', '2.2.2'])
Why are the visitor sets sharing data between what I thought should be separate instances of the Counter class. Shouldn't each input point to a specific instance?
What makes this more difficult to understand is that the hit counter seems to work fine and keep things separate.
Can anyone help me understand what's going on here or how to fix it?