[openstack-dev] [Review] Use of exception for non-exceptional cases

Thomas Hervé therve at gmail.com
Wed Jul 10 19:14:36 UTC 2013


On Wed, Jul 10, 2013 at 8:32 PM, Mark McLoughlin <markmc at redhat.com> wrote:

> On Wed, 2013-07-10 at 11:01 -0700, Nachi Ueno wrote:
> > Personally, I prefer not to use exception for such cases.
>

The key here is "personally". I don't think we have to agree on all style
issues.


>
> My instinct is the same, but EAFP does seem to be the python way. There
> are times I can tolerate the EAFP approach but, even then, I generally
> think LBYL is cleaner.
>
> I can live with something like this:
>
>   try:
>       return obj.foo
>   except AttributeError:
>       pass
>
> but this is obviously broken:
>
>   try:
>       return self.do_something(obj.foo)
>   except AttributeError:
>       pass
>
> since AttributeError will mask a typo with the do_something() call or an
> AttributeError raised from inside do_something()
>
> But I fail to see what's wrong with this:
>
>   if hasattr(obj, 'foo'):
>       return obj.foo
>

hasattr is a bit dangerous as it catches more exceptions than it needs too.
See for example
http://stackoverflow.com/questions/903130/hasattr-vs-try-except-block-to-deal-with-non-existent-attributes/16186050#16186050for
an explanation.

-- 
Thomas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openstack.org/pipermail/openstack-dev/attachments/20130710/888e9bff/attachment.html>


More information about the OpenStack-dev mailing list