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

Mark McLoughlin markmc at redhat.com
Thu Jul 11 08:50:27 UTC 2013


On Wed, 2013-07-10 at 21:14 +0200, Thomas Hervé wrote:
> 
> 
> 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.

When it results in a patch submitter getting a -1 from one person for
choosing EAFP and a -1 from another person for choosing LBYL, then
yes ... actually we do need to agree.

>         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#16186050 for an explanation.

That answer does begin with this, though:

  I almost always use hasattr: it's the correct choice for most cases.

and, frankly, a __getattr__() method that returns ValueError is broken.

i.e. the conclusion would be that we should only avoid hasattr() in some
very limited cases where the underlying __getattr__() does weird things
or where using it can result in a race condition.

Cheers,
Mark.





More information about the OpenStack-dev mailing list