[Tutor] checksum of dictionary
Erik Price
eprice@ptc.com
Thu Feb 13 11:16:09 2003
Magnus Lycka wrote:
>> Nowadays you can subclass the dictionary to make one that notices any
>> changes. If you're purely concerned about setitem and delitem calls, you
>> could just override those. If you want to catch update(), etc, you might
>> like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236,
>> which
>> is a dict interface defined in terms of getitem/setitem/delitem/keys.
>> It's
>> great for constructing custom dict-like objects that use custom code
>> for all 20-or-so of the standard dict methods.
>
>
> But notice that no such fix will see changes in mutable data in the
> dictionary.
I didn't even think of this myself, though I was thinking that rather
than subclass dict, it might be better to create a custom class that
contains its own instance of a dictionary, and instead of directly
accessing the dictionary, the class provides set and get methods for
setting and getting the data. Of course, within these methods is the
logic for testing whether or not the dict has been modified (perhaps by
using an enumeration or boolean flag).
Drawbacks, however:
1) You can't use convenient dictionary syntax, you have to use the
specified accessor/mutator methods. (Probably not that big a deal.)
2) I'm not sure of how this works in Python, but my guess is that if you
have some code that wants an object of type "dict", then this new object
won't do the trick, since it composes a dict but does not inherit from one.
Is this in fact how Python works, anybody? Since it's dynamically
typed, I'm not sure how much type really matters anyway, but in library
code it might be something to consider.
In Java there would probably be some interface that the new class could
implement so that it can be considered the same type as the dict, yet
without actually having to inherit from dict, but that is Java and this
is Python, and perhaps types just aren't as significant. I'm trying to
be a more knowledgeable Python programmer so if someone has a pointer to
more information on the significance of types in Python... :)
Erik