Last active
November 4, 2015 02:38
-
-
Save internetimagery/0cf2da198e95821c6252 to your computer and use it in GitHub Desktop.
Dict wrapper that tracks changes
This file contains hidden or 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
| try: | |
| import cPickle as pickle | |
| except ImportError: | |
| import pickle | |
| class Dict(dict): | |
| """ | |
| Dict that tracks changes. Changes = (New, Changed, Removed) | |
| """ | |
| def __init__(s, *args, **kwargs): | |
| dict.__init__(s, *args, **kwargs) | |
| s._diff = {}; s.diff | |
| def diff(): | |
| def fget(s): | |
| diff1 = set(dict.keys(s)) # Current keys | |
| diff2 = set(s._diff.keys()) # Old keys | |
| diff3 = dict((a, pickle.dumps(b, -1)) for a, b in dict.items(s)) # Changes | |
| new = diff1 - diff2 # New keys | |
| rem = diff2 - diff1 # Removed keys | |
| chg = set(a for a, b in diff3.items() if a in s._diff and a not in new and a not in rem and b != s._diff[a]) | |
| s._diff = diff3 | |
| return (new, chg, rem) if new or chg or rem else None | |
| def fset(s, v): | |
| if v: | |
| s._diff = {} | |
| else: | |
| s.diff | |
| return locals() | |
| diff = property(**diff()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment