Search code examples
pythonpython-3.xgetattr

Using getattr in python


The getattr function is defined as follows:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Which method does getattr() call? For example, does it call:

  • __getattr__
  • __get__
  • __getattribute__
  • something else?

Solution

  • getattr() goes to __getattribute__() first, same as the dot operator:

    >>> class A:
    ...     def __getattr__(self, obj):
    ...         print("Called __getattr__")
    ...         return None
    ...     def __getattribute__(self, obj):
    ...         print("Called __getattribute__")
    ...         return None
    ...     def __get__(self, obj):
    ...         print("Called __get__")
    ...         return None
    ... 
    >>> a = A()
    >>> a.foobar
    Called __getattribute__
    >>> getattr(a, 'foobar')
    Called __getattribute__
    

    Convention is to use getattr() only when you don't know at compile-time what the attribute name is supposed to be. If you do, then use the dot operator ("explicit is better than implicit"...).

    As @Klaus D. mentioned in a comment, the python Data Model documentation goes into more detail about how .__getattribute__() and .__getattr__() interact. Suffice it to say that, at a high level, the latter is a fall-back option of sorts for if the former fails. Note that .__getattr__() and the built-in getattr() are not directly related - IIRC this is a quirk of naming that originated in earlier versions of python and was granfathered into python 3.