How can I make an existing object read-only?
aleaxit at yahoo.com
Mon Oct 4 23:20:10 CEST 2004
Irmen de Jong <irmen at -nospam-remove-this-xs4all.nl> wrote:
> Maybe I'm way off track here, but I want to do something like this:
> Say I have an object that's initialized with a bunch of attributes.
> I want to pass the object to a piece of code that is not allowed
> to add/delete/set attributes on this object.
> When control returns, the code is again allowed to make changes
> to the object.
Instead of passing the bare object, pass it wrapped into something like:
def __init__(self, obj): self.__dict__['_obj'] = obj
def __getattr__(self, n): return getattr(self._obj, n)
def __setattr__(self, n, *args): raise AttributeError, n
__delattr__ = __setattr__
Of course this only helps avoid accidents, it doesn't give security
against malicious attacks (there's no known way to do that today in
Python). I'm also assuming that the "piece of code" IS allowed to
access any attribute and call any method of obj (including methods which
might internally set attributes, whatever), if you want to add further
prohibitions that shouldn't be too hard, though.
More information about the Python-list