__getattr__ and other customization methods

Mark Hammond MarkH at ActiveState.com
Sun Jun 17 19:50:03 EDT 2001


Brian Quinlan wrote:

> Is there any reason why getattr, when called on an instance, should call
> that instance's __getattr__ method for other customization methods
> (methods starting with __)? 


Otherwise you have no way of saying "this method does not exist".

Consider an object that wraps another object - ie, a proxy.

Some objects you proxy may provide a __len__ method, while others may 
not.  However, Python changes behaviour based on the *existence* of this 
method.  Generally you will want your proxy to behave exactly the same 
as the proxied object.

So, if the proxy class always provides a __len__ method, it loses this 
ability - what would __len__ return if the proxied object does not 
provide the method?  The only reasonable way is to have __getattr__ ask 
for these attributes.

Further, it is, IMO, much cleaner this way.  Special method names are 
just attributes.  The lack of surprises here makes for a cleaner model. 
  I agree there are gotchyas, but I don't think it should be any different.

And finally, changing this would break too much code, so I seriously 
doubt it will happen.

Mark.




More information about the Python-list mailing list