[openstack-dev] [Review] Use of exception for non-exceptional cases
nachi at ntti3.com
Wed Jul 10 20:44:46 UTC 2013
2013/7/10 Doug Hellmann <doug.hellmann at dreamhost.com>:
> On Wed, Jul 10, 2013 at 3:57 PM, David Ripton <dripton at redhat.com> wrote:
>> On 07/10/2013 02:01 PM, 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'
>> Both of these are fine. Neither deserves to be banned.
OK if there is no preference in the community, I'l review it as 'This
is my personal opinion but you can choose option'.
>> But LBYL is often naive in the face of concurrency. Just because
>> something was true a microsecond ago doesn't mean it's still true.
>> Exceptions are often more robust.
> getattr() takes a default and, as it is implemented in C, is thread-safe.
> value = getattr(my_obj, 'might_not_be_there', 'default')
> Of course, it's probably better to make sure you've always got the same type
> of object in the first place but sometimes the attributes change across
> versions of libraries.
> For accessing elements of a sequence that may be too short,
> itertools.chain() and itertools.islice() are useful.
>>>> import itertools
>>>> vals1 = ['a', 'b']
>>>> a, b, c = itertools.islice(itertools.chain(vals1, ['c']), 3)
>>>> a, b, c
> ('a', 'b', 'c')
>>>> vals2 = ['a', 'b', 'd']
>>>> a, b, c = itertools.islice(itertools.chain(vals2, ['c']), 3)
>>>> a, b, c
> ('a', 'b', 'd')
I like this way! :)
> OpenStack-dev mailing list
> OpenStack-dev at lists.openstack.org
More information about the OpenStack-dev