converting a nested try/except statement into try/except/else

Boris Borcic bborcic at gmail.com
Thu Aug 10 17:25:11 EDT 2006


Bruno Desthuilliers wrote:
> Boris Borcic a écrit :
>> Slawomir Nowaczyk wrote:
>>
>>>
>>> try:
>>>     if int(text) > 0:
>>>        return True
>>> except ValueError:
>>>     pass
>>> self.error_message()
>>> return False
>>>
>>
>> Nicely DRY. To make it even more compact, it may be noticed that the 
>> default return value None is false in a boolean context - so that the 
>> last line is superfluous if the return value is only wanted to test it 
>> in such a context.
> 
> While it's technically true - and I while I have a taste for compactness 
> - skipping the explicit 'return False' somehow hurts my sense of 
> esthethic... Unless you propose to return object or type  instead of 
> True - but then it begins to look very strange !-)

so what about simplifying your solution 1 to

try :
     return int(text)>0 or int('garbage')
except ValueError :
     self.error_message()


it still returns True on success, but hides it well :) and while perhaps a bit 
too clever I feel it competes well on readability, precisely because it is 
compact and because int('garbage') mimics int(text) while standing just before 
'except ValueError'. That mimicry kind of encapsulates your and infidel's answer 
to the OP's objection to raising ValueError if int(text)<=0.




More information about the Python-list mailing list