[Python-Dev] 'hasattr' is broken by design

Yury Selivanov yselivanov at gmail.com
Tue Aug 24 00:22:31 CEST 2010


> On 2010-08-23, at 6:17 PM, Benjamin Peterson wrote:
> 2010/8/23 Yury Selivanov <yselivanov at gmail.com>:
>>> On 2010-08-23, at 6:00 PM, Guido van Rossum wrote:
>>> On Mon, Aug 23, 2010 at 2:22 PM, Yury Selivanov <yselivanov at gmail.com> wrote:
>> BTW, is it possible to add new magic method __hasattr__?  Maybe not
>> in Python 3.2, but in general.
> 
> -1 The whole point of hasattr() is that getattr() on that attribute
> would return something. Let's not destroy that.

By default, if you don't overload __hasattr__, it will do exactly that.

But let's imagine the situation in some ORM.  Sometimes, engine knows that
attribute exists even before executing it (which leads to querying DB), and
thus it is possible to return True in the overloaded __hasattr__.

Example:
... if hasattr(entity, 'title'): # <- __hasattr__ has the info in metadata,
                                 #    no query to DB
...     title = entity.title     # <- now, we can query the DB

So, the proposed magic method is not intended to change the protocol,
but to complement and enhance it.

-
Yury


More information about the Python-Dev mailing list