On Wed, Jul 10, 2013 at 8:32 PM, Mark McLoughlin <[email protected]> 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
_______________________________________________ OpenStack-dev mailing list [email protected] http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev
