[Python-ideas] AtributeError inside __get__
Nick Coghlan
ncoghlan at gmail.com
Sun Dec 25 21:04:58 EST 2016
On 26 December 2016 at 04:24, Zahari Dim <zaharid at 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 | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161226/64cc20bc/attachment.html>
More information about the Python-ideas
mailing list