469,923 Members | 1,777 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,923 developers. It's quick & easy.

__getattribute__ and __getattr__

Hi,
In the Python documentation regarding __getattribute__ (more attribute
access for new style classes) it is mentioned that if __getattribute__
is defined __getattr__ will never be called (unless called explicitely).
Here is the exact citation:

"""
The following methods only apply to new-style classes.

__getattribute__( self, name)
Called unconditionally to implement attribute accesses for
instances of the class. If the class also defines __getattr__, it will
never be called (unless called explicitly). This method should return
the (computed) attribute value or raise an AttributeError exception. In
order to avoid infinite recursion in this method, its implementation
should always call the base class method with the same name to access
any attributes it needs, for example, "object.__getattribute__(self,
name)".
"""

I discovered that it is not so for Python 2.3.4 on Windows at least. The
actual behavior is that if both __getattribute__ and __getattr__ methods
exist then __getattribute__ is called first, but if it raises
AttributeError then the exception will be swallowed silently and
__getattr__ will be invoked. Note that if I forward to the default
object.__getattribute__ or if I raise the AttributeError myself the
result is the same. My understanding of the documentation is it that the
program should just exit with the AttributeError exception.

Here is the code:

class A(object):
def __getattribute__(self, name):
return object.__getattribute__(self, name)
# raise AttributeError()

def __getattr__(self, name):
return 42

if __name__ == '__main__':
a = A()
print a.x

Here is the Output:

42
Jul 19 '05 #1
0 6401

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Daniel Schüle | last post: by
2 posts views Thread by Henry 'Pi' James | last post: by
1 post views Thread by pascal.parent | last post: by
6 posts views Thread by Adam Donahue | last post: by
4 posts views Thread by Enrico | last post: by
8 posts views Thread by bukzor | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.