On 26 December 2016 at 04:24, Zahari Dim <zaha...@gmail.com> wrote:

> Hi,
>
> The other day I came across a particularly ugly bug. A simplified case
> goes like:
>
> class X:
>     @property
>     def y(self):
>         return self.nonexisting
>
> hasattr(X(),'y')
>
> This returns False because hasattr calls the property which in turn
> raises an AttributeError which is used to determine that the property
> doesn't exist, even if it does. This is arguably unexpected and
> surprising and can be very difficult to understand if it happens
> within a large codebase. Given the precedent with generator_stop,
> which solves a similar problem for StopIteration, I was wondering if
> it would be possible to have the __get__ method convert the
> AttributeErrors raised inside it to RuntimeErrors.
>
> The situation with this is a little more complicated because there
> could be a (possibly strange) where one might want to raise an
> AttributeError inside __get__.


There are a lot of entirely valid properties that look something like this:


    @property
    def attr(self):
        try:
            return data_store[lookup_key]
        except KeyError:
            raise AttributeError("attr")

And unlike StopIteration (where either "return" or "raise StopIteration"
could be used), that *is* the way for a property method to indicate
"attribute not actually present".

This is one of the many cases where IDEs with some form of static
structural checking really do make development easier - the
"self.nonexisting" would be flagged as non-existent directly in the editor,
even before you attempted to run the code.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to