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

Dolph Mathews dolph.mathews at gmail.com
Wed Jul 10 20:50:17 UTC 2013


On Wed, Jul 10, 2013 at 3:30 PM, Doug Hellmann
<doug.hellmann at dreamhost.com>wrote:

>
>
>
> 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
>>>
>>> try:
>>>     value = list[5]
>>> except IndexError:
>>>      value = 'default_value'
>>>
>>> This can be also written as,
>>>
>>>       list_a[3] if len(list_a) > 3 else 'default_value'
>>>
>>
>> Both of these are fine.  Neither deserves to be banned.
>>
>> 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.
> So:
>
>   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')
>

++ every time I look at itertools it's doing something clever


>
> Doug
>
>
> _______________________________________________
> OpenStack-dev mailing list
> OpenStack-dev at lists.openstack.org
> http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev
>
>


-- 

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


More information about the OpenStack-dev mailing list