Hi everybody, I'm looking at pxdom and in particular at its foundation class DOMObject (source code at the end of the message). In it, the author attempts to allow the establishment of readonly and read&write attributes through the special methods __getattr__ and __setattr__. In so doing is possible to create subclasses such as:
class MyClass(DOMObject): def __init__(self): DOMObject.__init__(self) self._anAttribute = "im_a_readonly_attribute" ## The presence of the following method allows ## read-only access to the attribute without the ## underscore, i.e.: aVar = myClassInstance.anAttribute def _get_anAttribute(self): return self._anAttribute ## Uncommenting the following line allows the setting of "anAttribute". ## Commented, the same action would raise an exception. ## def _set_anAttribute(self, value): self._anAttribute = value This is all good and dandy and it works, mostly. However, if you look at the code below for the method __getattr__, it appears to be attempting to prevent direct access to -any- variable starting with an underscore. def __getattr__(self, key): if key[:1]=='_': raise AttributeError, key But access isn't actually prevented because __getattr__ is invoked - only- if an attribute is not found by normal means. So, is it just me or that little snipped of code either has another purpose or simply doesn't do the intended job? Manu ----- class DOMObject: """Base class for objects implementing DOM interfaces Provide properties in a way compatible with old versions of Python: subclass should provide method _get_propertyName to make a read- only property, and also _set_propertyName for a writable. If the readonly property is set, all other properties become immutable. """ def __init__(self, readonly= False): self._readonly= readonly def _get_readonly(self): return self._readonly def _set_readonly(self, value): self._readonly= value def __getattr__(self, key): if key[:1]=='_': raise AttributeError, key try: getter= getattr(self, '_get_'+key) except AttributeError: raise AttributeError, key return getter() def __setattr__(self, key, value): if key[:1]=='_': self.__dict__[key]= value return # When an object is readonly, there are a few attributes that can be set # regardless. Readonly is one (obviously), but due to a wart in the DOM # spec it must also be possible to set nodeValue and textContent to # anything on nodes where these properties are defined to be null (with no # effect). Check specifically for these property names as a nasty hack # to conform exactly to the spec. # if self._readonly and key not in ('readonly', 'nodeValue', 'textContent'): raise NoModificationAllowedErr(self, key) try: setter= getattr(self, '_set_'+key) except AttributeError: if hasattr(self, '_get_'+key): raise NoModificationAllowedErr(self, key) raise AttributeError, key setter(value) -- http://mail.python.org/mailman/listinfo/python-list