<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On 26 December 2016 at 04:24, Zahari Dim <span dir="ltr"><<a href="mailto:zaharid@gmail.com" target="_blank">zaharid@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi,<br>
<br>
The other day I came across a particularly ugly bug. A simplified case<br>
goes like:<br>
<br>
class X:<br>
@property<br>
def y(self):<br>
return self.nonexisting<br>
<br>
hasattr(X(),'y')<br>
<br>
This returns False because hasattr calls the property which in turn<br>
raises an AttributeError which is used to determine that the property<br>
doesn't exist, even if it does. This is arguably unexpected and<br>
surprising and can be very difficult to understand if it happens<br>
within a large codebase. Given the precedent with generator_stop,<br>
which solves a similar problem for StopIteration, I was wondering if<br>
it would be possible to have the __get__ method convert the<br>
AttributeErrors raised inside it to RuntimeErrors.<br>
<br>
The situation with this is a little more complicated because there<br>
could be a (possibly strange) where one might want to raise an<br>
AttributeError inside __get__.</blockquote><br></div>There are a lot of entirely valid properties that look something like this:<br><br><br></div><div class="gmail_extra"> @property<br></div><div class="gmail_extra"> def attr(self):<br></div><div class="gmail_extra"> try:<br></div><div class="gmail_extra"> return data_store[lookup_key]<br></div><div class="gmail_extra"> except KeyError:<br></div><div class="gmail_extra"> raise AttributeError("attr")<br></div><div class="gmail_extra"><br></div><div class="gmail_extra">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".<br><br></div><div class="gmail_extra">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.<br></div><div class="gmail_extra"><br></div><div class="gmail_extra">Cheers,<br></div><div class="gmail_extra">Nick.<br clear="all"></div><div class="gmail_extra"><br>-- <br><div class="gmail_signature" data-smartmail="gmail_signature">Nick Coghlan | <a href="mailto:ncoghlan@gmail.com" target="_blank">ncoghlan@gmail.com</a> | Brisbane, Australia</div>
</div></div>