[Python-Dev] hasattr and properties

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Dec 8 01:05:14 CET 2005


Thomas Lotze wrote:

> Apparently, when applied to a class instance, hasattr calls getattr and
> decides that the attribute doesn't exist if the call raises any exception.
 > - Wouldn't it make sense to only report a missing attribute if an
 > AttributeError is raised?

That would be an improvement, but calling the property access
code as a side effect of hasattr seems like a misfeature to me
in the first place.

> - As far as properties are concerned, it would make even more sense to not
> call getattr but try to look up the attribute the same way getattr would.
> This would, however, not work consistently anymore if one customizes
> attribute access.

Maybe descriptors need a fourth slot for hasattr
customisation?

The logic would then be

   if there is a descriptor for the attribute:
     if the descriptor's hasattr slot is populated:
       return the result of calling it
     else:
       return True
   else:
     look in the instance dict for the attribute

There wouldn't be a need to rely on catching exceptions
at all, then.

-- 
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+


More information about the Python-Dev mailing list