[Python-Dev] hasattr and properties

Calvin Spealman ironfroggy at gmail.com
Thu Dec 8 07:45:20 CET 2005


On 12/7/05, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> 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.

I will have to disagree with you there. If hasattr(a,b) returns True,
one should be able to expect a.b will work properly. Otherwise, the
majority of use cases for hasattr will be completely thrown out the
window. How can hasattr work properly with properties if it doesn't
call the property access code?

> > - 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.

If there is a descriptor with no hasattr slot, it should call __get__
to make sure it is successful (ie, doesn't raise any exceptions).


More information about the Python-Dev mailing list