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

Yury Selivanov yselivanov at gmail.com
Tue Aug 24 00:12:09 CEST 2010


> 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:
>> As I understand the only possible way to make 'hasattr' work as it name indicates (i.e. just check if attribute exists, not run it), is to add another magic method(s?) to the existing __getattr__ and __getattribute__ which will tell whether attribute exists or not, and by default this method would mimic current 'hasattr' behaviour.
> 
> You nailed it. At the lowest level (either in C or in Python) there is
> no way to check for an attribute's presence without getting its value.
> This has so far been fundamental, and everything else is just
> appearances.
> 
> I propose that this is good enough and that we should at this point
> not try to invent another protocol, just decide whether hasattr() can
> be fixed (and leaving PyObject_HasAttr*() alone).

BTW, is it possible to add new magic method __hasattr__?  Maybe not
in Python 3.2, but in general.

The more I think about it the more I like the idea.  By default, 'hasattr'
would check MRO for the attribute, if not found - check for __hasattr__,
if not found - fallback to the current schema with 'getattr'.

This would not break any current code, but open a lot of potential 
(especially for things that implement some lazy loading protocols).

From the performance point of view, I believe it shouldn't change much,
as current 'hasattr' which uses 'getattr' which calls __getattr(ibute)__ 
methods.

I know this is much more then just fixing exception swallowing, but this
is somewhat required functionality to complete the current dynamism 
python offers.

-
Yury


More information about the Python-Dev mailing list