<br><br><div class="gmail_quote">On Wed, Jul 10, 2013 at 8:32 PM, Mark McLoughlin <span dir="ltr"><<a href="mailto:markmc@redhat.com" target="_blank">markmc@redhat.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">On Wed, 2013-07-10 at 11:01 -0700, Nachi Ueno wrote:<br></div><div class="im">
> Personally, I prefer not to use exception for such cases.<br></div></blockquote><div><br></div><div>The key here is "personally". I don't think we have to agree on all style issues.</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">
<br>
</div>My instinct is the same, but EAFP does seem to be the python way. There<br>
are times I can tolerate the EAFP approach but, even then, I generally<br>
think LBYL is cleaner.<br>
<br>
I can live with something like this:<br>
<br>
try:<br>
return obj.foo<br>
except AttributeError:<br>
pass<br>
<br>
but this is obviously broken:<br>
<br>
try:<br>
return self.do_something(obj.foo)<br>
except AttributeError:<br>
pass<br>
<br>
since AttributeError will mask a typo with the do_something() call or an<br>
AttributeError raised from inside do_something()<br>
<br>
But I fail to see what's wrong with this:<br>
<br>
if hasattr(obj, 'foo'):<br>
return obj.foo<br></blockquote><div><br></div><div>hasattr is a bit dangerous as it catches more exceptions than it needs too. See for example </div><div><a href="http://stackoverflow.com/questions/903130/hasattr-vs-try-except-block-to-deal-with-non-existent-attributes/16186050#16186050">http://stackoverflow.com/questions/903130/hasattr-vs-try-except-block-to-deal-with-non-existent-attributes/16186050#16186050</a> for an explanation.</div>
<div><br></div><div>-- </div><div>Thomas</div><div> </div></div>