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

Benjamin Peterson benjamin at python.org
Tue Aug 24 00:25:18 CEST 2010


2010/8/23 Yury Selivanov <yselivanov at gmail.com>:
>> 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

In this case, I think it would make more sense to ask the model:
type(entity).has_property("title")

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

But it still raises the potential to break the relationship between
hasattr and getattr.

I think this should require a PEP.



-- 
Regards,
Benjamin


More information about the Python-Dev mailing list