How can I make an existing object read-only?
Irmen de Jong
irmen at -nospam-remove-this-xs4all.nl
Mon Oct 4 17:47:37 EDT 2004
Alex Martelli wrote:
(and Steven Bethard also, essentially)
> Instead of passing the bare object, pass it wrapped into something like:
>
> class nowrite:
> 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__
>
Now that was simple, why didn't I think of that myself.
Too much Java coding apparently clogs up your mind :o)
> 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).
Yes, I am aware of that. It was purely to 'avoid accidents'.
Incidentally, why are you writing:
def __setattr__(self, n, *args): ...
with a varg list ? I always assumed it only got a single 'value' parameter?
Thanks
--Irmen.
More information about the Python-list
mailing list