[Fwd: Re: Pythonic way to determine if a string is a number]

Tim Golden mail at timgolden.me.uk
Mon Feb 16 05:03:02 EST 2009


[Resending after a bounce from mailing list]

python at bdurham.com wrote:
>> try:
>>    float (input)
>> except ValueError:
>>    return False
>> else:
>>    return True
> 
> I follow the semantics, but I don't know why I would prefer the try/else
> technique over the simpler:
> 
> try:
>     float( input )
>     return True
> except ValueError:
>     return False


In this case, I don't think you would. At least I would
say it's no more than 50/50 depending on taste and probably
more like 60/40 in favour of your solution. However
there are situations where try-except-else more 
naturally expresses the code intent. Of course I
can't think of a single one now, and it's not an easy
thing to search my codebase for so I'll just press send
and then think of an example two seconds later!

Really wanted to make sure you were aware of it as an
option; the else clause on try-except (and its cousin
the for-else clause) are easily overlooked / forgotten.

TJG




More information about the Python-list mailing list