In short: what’s the fasted way to check if a huge list in python has changed? hashlib needs a buffer, and building a string representation of that list is unfeasible.
In long: I’ve got a HUGE list of dictionaries representing data. I run a number of analyses on this data, but there are a few meta-data aspects that are required by all of the analyses, ie. the the set of subjects (each dict in the list has a subject key, and at times I just need a list of all subject who have data present in the data set.). So I’d like to implement the following:
class Data:
def __init__(self, ...):
self.data = [{...}, {...}, ...] # long ass list of dicts
self.subjects = set()
self.hash = 0
def get_subjects(self):
# recalculate set of subjects only if necessary
if self.has_changed():
set(datum['subject'] for datum in self.data)
return self.subjects
def has_changed(self):
# calculate hash of self.data
hash = self.data.get_hash() # HOW TO DO THIS?
changed = self.hash == hash
self.hash = hash # reset last remembered hash
return changed
The question is how to implement the has_changed method, or more specifically, get_hash (each object already has a __hash__ method, but by default it just returns the object’s id, which doesn’t change when we e.g. append an element to a list).
A more sophisticated approach there would be to work with proxy data elements instead of native lists and dictionaries, which could flag any change to their attributes. To make it more flexible, you could even code a callback to be used in case of any changes.
So, assuming you only have to deal with lists and dictionaries on your data structure – we can work with classes inheriting from dict and list with a callback when any data changing method on the object is accessed The full list of methods is in http://docs.python.org/reference/datamodel.html
2017 update
One does live and learn: native lists can be changed by native methods by calls that bypass the magic methods. The fool proof system is the same approach, but inheriting from
collections.abc.MutableSequenceinstead, nd keeping a native list as an internal attribute of your proxy object.