__getattribute__ and __getattr__

Discussion in 'Python' started by Gigi, May 29, 2005.

  1. Gigi

    Gigi Guest

    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
    Gigi, May 29, 2005
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Stefan Sonnenberg-Carstens

    newstyle classes and __getattribute__

    Stefan Sonnenberg-Carstens, Oct 28, 2005, in forum: Python
    Replies:
    5
    Views:
    295
    Stefan Sonnenberg-Carstens
    Oct 28, 2005
  2. Replies:
    1
    Views:
    325
    Peter Otten
    Apr 17, 2006
  3. Pedro Werneck
    Replies:
    4
    Views:
    417
    Pedro Werneck
    Aug 8, 2006
  4. Giampaolo Rodolà

    __getattribute__ and methods proxying

    Giampaolo Rodolà, Jun 12, 2010, in forum: Python
    Replies:
    0
    Views:
    230
    Giampaolo Rodolà
    Jun 12, 2010
  5. ernest
    Replies:
    2
    Views:
    288
    ernest
    Jul 16, 2010
Loading...

Share This Page