How can I make an existing object read-only?
Irmen de Jong
irmen at -nospam-remove-this-xs4all.nl
Mon Oct 4 22:55:21 CEST 2004
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.
I know; "we're all adults, just don't change the attributes!", but
the following code more or less seems to work:
def __setattr__(self, name, value):
raise AttributeError, "page object is read-only"
self.__dict__[name] = value
and then controlling the setattr by setting _page_readonly.
Now I was wondering: isn't there another way?
Because the objects involved have quite a few attributes,
and initializing the objects will now call my custom setattr
method for every attribute. The code concerned is more or less
time-critical so I'd rather not have this custom setattr method
when initializing the object...
Is there another way to hack this? Am I making sense at all? ;-)
More information about the Python-list