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

  • Thread starter Christoph Becker-Freyseng
  • Start date
C

Christoph Becker-Freyseng

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top