I am trying to override getattr method and as per my understanding there should be infinite loop in the following code snippet as by default object.__getattribute__(self,attr) is invoked which will invoke overrided getattr method as attribute 'notpresent' is not present in namespaces and this process will be keep on repeating. Can anybody help me in figuring out that why this behavior is not observed here.
Moreover I am unable to figure out that why AttributeError is not raised when implicit call to getattribute is done while accessing attribute using dot notation while it is being raised second time when we are trying to invoke getattribute explicitly within method
class Test(object):
#Act as a fallback and is invoked when getattribute is unable to find attribute
def __getattr__(self,attr):
print "getattr is called"
return object.__getattribute__(self,attr) #AttributeError is raised
t=Test([1,2,3,4])
b = t.notpresent
You are calling object.__getattribute__
within Test.__getattr__
.
There is no loop involved here.
Moreover, as per the docs, __getattribute__
does not implicitly call __getattr__
.
Here is the C-implementation of the __getattribute__
call. Especially the slot_tp_getattr_hook
part.
In your case, the attribute lookup failure lead to the execution of line 6072 that calls your custom __getattr__
function.
From there on, the AttributeError
has been cleared. But your call to object.__getattribute__
will set it back and line 6074 or 6075 won't handle it.
The object.__getattribute__
call is implemented like so and thus (re)raise AttributeError
(line 1107).