forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchange_tracker.py
More file actions
51 lines (35 loc) · 1.45 KB
/
change_tracker.py
File metadata and controls
51 lines (35 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
import pickle
from python_toolbox.nifty_collections import WeakKeyIdentityDict
class ChangeTracker:
'''
Tracks changes in objects that are registered with it.
To register an object, use `.check_in(obj)`. It will return `True`. Every
time `.check_in` will be called with the same object, it will return
whether the object changed since the last time it was checked in.
'''
def __init__(self):
self.library = WeakKeyIdentityDict()
'''dictoid mapping from objects to their last pickle value.'''
def check_in(self, thing):
'''
Check in an object for change tracking.
The first time you check in an object, it will return `True`. Every
time `.check_in` will be called with the same object, it will return
whether the object changed since the last time it was checked in.
'''
new_pickle = pickle.dumps(thing, 2)
if thing not in self.library:
self.library[thing] = new_pickle
return True
# thing in self.library
previous_pickle = self.library[thing]
if previous_pickle == new_pickle:
return False
else:
self.library[thing] = new_pickle
return True
def __contains__(self, thing):
'''Return whether `thing` is tracked.'''
return self.library.__contains__(thing)