Immutable Proxy-Class, "Pseudo freeze(obj)"

Christoph Becker-Freyseng webmaster at beyond-thoughts.com
Mon Jan 12 17:05:49 EST 2004


Hello,

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?
Badstyle?
Handy?
...


Thanks,
    Christoph Becker-Freyseng


PS:
Some links on similar subjects:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159143    ASPN : 
Python Cookbook : A ThreadedProxy wrapper

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078
ASPN : Python Cookbook : Wrapping method calls (meta-class example)

http://www.python.org/doc/current/ref/customization.html
3.3.1 Basic customization

http://www.python.org/search/hypermail/python-recent/0556.html
Python Archive (recent): freezing structures.

http://gpk.wftp.org:8082/sets.html
Python: module sets








More information about the Python-list mailing list