Conceptual flaw in pxdom?
Peter Otten
__peter__ at web.de
Tue May 19 11:57:30 EDT 2009
Emanuele D'Arrigo wrote:
> 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?
It doesn't do what you think it does; it is there to prevent "infinite"
recursion. Have a look at the complete method:
> def __getattr__(self, key):
> if key[:1]=='_':
> raise AttributeError, key
> try:
> getter= getattr(self, '_get_'+key)
> except AttributeError:
> raise AttributeError, key
> return getter()
If you instantiate the object and try to access the -- non-existent --
attribute yadda __getattr__() will be called with key="yadda" which doesn't
start with an underscore and with gettattr(self, "_get_yadda") triggers
another __getattr__() call as _get_yadda doesn't exist either. If the check
weren't there yet another getattr(self, "_get__get_yadda") call would
follow, and so on until the recursion limit is reached.
Peter
More information about the Python-list
mailing list