Created
February 4, 2014 04:56
-
-
Save zapman449/8798362 to your computer and use it in GitHub Desktop.
DeltaDict A dictionary for tracking the deltas between updates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
DeltaDict: A python dictionary for keeping track of the delta between numeric | |
values. | |
Insert a number in a key, and you'll get that number back. Next insert a | |
higher number. Now a get() will return the delta between the numbers. | |
Useful for monitoring applications where you're presented with a monotomically | |
increasing counter, but only really care about the deltas. | |
Future improvement: flag into __init__() to allow absolute value deltas | |
instead of wrapping around at zero. | |
""" | |
import collections | |
class DeltaDict(collections.MutableMapping) : | |
def __init__(self, *args, **kwargs): | |
self.store = dict() | |
self.delta_store = dict() | |
self.update(dict(*args, **kwargs)) # use the free update to set keys | |
def __getitem__(self, key): | |
#return self.store[self.__keytransform__(key)] | |
return self.delta_store[key] | |
def __setitem__(self, key, value): | |
if not self.store.has_key(key) or value < self.store[key] : | |
self.store[key] = value | |
self.delta_store[key] = value | |
else : | |
curval = self.store[key] | |
self.delta_store[key] = value - curval | |
self.store[key] = value | |
#self.store[key] = value | |
def __delitem__(self, key): | |
del self.store[key] | |
del self.delta_store[key] | |
def __iter__(self): | |
return iter(self.delta_store) | |
def __len__(self): | |
return len(self.store) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment