[Tutor] Re: converting string to a number

nik my.mailing.lists at noos.fr
Thu Sep 2 18:01:24 CEST 2004


Kent Johnson wrote:

> At 02:39 PM 9/2/2004 +0000, Andrei wrote:
>
>> If you have doubts about something being a builtin, you can try it in 
>> the
>> interactive interpreter, like this:
>>
>>   >>> 'str' in dir(__builtins__)
>>   True
>>   >>> 'apples' in dir(__builtins__)
>>   False
>
>
> or just type the name itself:
> >>> str
> <type 'str'>
> >>> apples
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'apples' is not defined
>
>> >       # do my number stuff
>> > except:
>> >       text = str
>> >       # do my string stuff
>> >
>> > then it's using the exception handling like an if statement. This 
>> feels kinda
>> wrong (hacky or lazy).
>>
>> It isn't wrong, it's in fact very good. I can't even think of a 
>> better way to do
>> it. You'll just need to pay attention to the possibility that "do my 
>> number
>> stuff" might cause an exception as well (e.g. if you try to divide 
>> something by
>> your number and number happens to be 0, you'll get a 
>> ZeroDivisionError), thereby
>> causing the code to interpret your number as a string anyway. Whether 
>> you want
>> this or not, I don't know.
>
>
> To guard against these possibilities, you can do two things:
> 1. Catch the actual exception that will be thrown (ValueError) instead 
> of catching everything.
> 2. Use try / except / else to remove "do my number stuff" from the try 
> block, so any exception thrown from it (even ValueError) will be 
> propagated to the caller.
>
> Like this:
> >>> def maybeNumber(val):
> ...   try:
> ...     number = float(val)
> ...   except ValueError:
> ...     text = val
> ...     print text, 'is a string'
> ...   else:
> ...     print number, 'is a number'
> ...
> >>> maybeNumber(1)
> 1.0 is a number
> >>> maybeNumber('ab')
> ab is a string
>
> Kent (who is finally starting to understand what try / except / else 
> is good for...)
>
>

Thanks for the advice guys, I hadn't thought of what would happen if it 
wasn't the exception you were expecting. It still feels uncomfortable 
though, I've always felt an exception is *exceptional*, ie something 
that was outside your control. However, I'm happy enough now to go and 
use it...

nik





More information about the Tutor mailing list