Immutable Proxy-Class, "Pseudo freeze(obj)"
webmaster at beyond-thoughts.com
Mon Jan 12 23:05:49 CET 2004
There are many cases where you have a mutable object and would like to
use its __hash__-method (e.g. use it as key for a dict). Of course a
mutable class should not define __hash__ because it doesn't make much
sense if the object can change.
However you could define the class Immutable (if you mind about
isinstance you can define a special __new__ ...) that is effectivly a
proxy for the object given the constructor so it passes all accesses to
the real object. But it defines a __hash__ method. This return a
hash-value calculated when the Immutable-instance has been created. Each
time there is an access to the underlying real object the proxy checks
if the newly-calculated hash-value and the old one (calculated on
instantiation) are different before and after access. If they are
different it will raise an Exception.
Since there is no way to prevent someone to keep a reference to the
original/real object obj it is not possible to avoid changing this
object. But then if the Immutable(obj)-instance is accessed the
hash-value will have changed. Thus causing an Exception.
One problem I see is that you can't find out where such an "illegal
operation" happened. You just see when the Immutable-instance is access
and it fails.
On the other hand if the Immutable-instance isn't accessed anymore
changing the original object is no problem.
What do you think?
Some links on similar subjects:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159143 ASPN :
Python Cookbook : A ThreadedProxy wrapper
ASPN : Python Cookbook : Wrapping method calls (meta-class example)
3.3.1 Basic customization
Python Archive (recent): freezing structures.
Python: module sets
More information about the Python-list