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

Guido van Rossum guido at python.org
Tue Aug 24 04:37:03 CEST 2010


Yuri, I think you are making a good case (though I would like for you
to be a good citizen and use the bug tracker to submit this for
review). Benjamin, what do you think?

--Guido

On Mon, Aug 23, 2010 at 7:14 PM, Yury Selivanov <yselivanov at gmail.com> wrote:
>> On 2010-08-23, at 10:56 AM, Guido van Rossum wrote:
>> On Mon, Aug 23, 2010 at 7:46 AM, Benjamin Peterson <benjamin at python.org> wrote:
>>> 2010/8/23 Yury Selivanov <yselivanov at gmail.com>:
>>>> 1) I propose to change 'hasattr' behaviour in Python 3, making it to swallow only AttributeError exceptions (exactly like 'getattr').  Probably, Python 3.2 release is our last chance.
>>>
>>> I would be in support of that.
>>
>> I am cautiously in favor. The existing behavior is definitely a
>> mistake and a trap. But it has been depended on for almost 20 years
>> now.
>>
>> I recommend that you create a patch, apply it, run the *entire* stdlib
>> test suite and see how much breaks. That will give you an idea of the
>> damage to expect for 3rd party code.
>
> Have done a little testing.
>
> The patch to builtin 'hasattr' function is trivial, and can be found
> attached to this letter (with the corresponding unittest):
>
> -        if (!PyErr_ExceptionMatches(PyExc_Exception))
> +        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
>
> So, after applying it, hasattr swallows only AttributeError exceptions.
>
>
> All tests from Python 3.2 test suite were good.
>
> After that, I've applied the patch on Python 2.6 and tested SqlAlchemy,
> Django and Twisted.
>
> - SqlAlchemy has failed three unittests, but those tests were designed
> specifically to handle 'hasattr' weird behaviour, so we can consider
> the change has no impact on SqlAlchemy.
>
> - Twisted - failed 3 tests out of ~3200, but it fails them on the same
> machine on an unpatched Python too, and they seem unrelated.
>
> - Django - all tests passed.
>
>
> I tested our internal company framework (~100K LOC) and, again, all
> tests passed.
>
>
>



-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list