[openstack-dev] [Review] Use of exception for non-exceptional cases
markmc at redhat.com
Wed Jul 10 18:32:55 UTC 2013
On Wed, 2013-07-10 at 11:01 -0700, Nachi Ueno wrote:
> HI folks
> I would like to ask the review criteria in the community.
> Should we use exception for non-exceptional cases when we can use
> parameter checking?
> Example1: Default value for array index
> value = list
> except IndexError:
> value = 'default_value'
> This can be also written as,
> list_a if len(list_a) > 3 else 'default_value'
> "ask for forgiveness, not permission" is one of way in python,
> however, on the other hand, google python code style guide says,
> Minimize the amount of code in a try/except block. The larger the body
> of the try, the more likely that an exception will be raised by a line
> of code that you didn't expect to raise an exception. In those cases,
> the try/except block hides a real error.
I don't think this statement contradicts the intent of EAFP.
> Personally, I prefer not to use exception for such cases.
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:
but this is obviously broken:
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'):
More information about the OpenStack-dev