Odd ValueError using float

Chris Angelico rosuav at gmail.com
Fri Mar 13 23:09:37 EDT 2015


On Sat, Mar 14, 2015 at 1:33 PM, Paul Rubin <no.email at nospam.invalid> wrote:
> emile <emile at fenx.com> writes:
>> *** NameError: name 'val' is not defined
>> (Pdb) l
>> 139         try:
>> 140             val = round(float(decval),1)
>> 141         except:
>> 142             import pdb; pdb.set_trace()
>
> If 'float' or 'round' throw an exception, the assignment to 'val' never
> happens, so 'val' is undefined.  Try examining the value of 'decval' in
> the debugger to see what is making the conversion fail.

That's exactly what the OP did :) Trouble is, it didn't help, because
it sure looked as if decval was the string '4'. My best guess was -
and is - that it's not just a string. We're looking at an SQL
interface routine here, so it may be that there's a string subclass
that length-limits itself, on the assumption that it's going into a
fixed-length database field. Let's see if I can recreate the OP's
situation...

>>> def Char(maxlen):
    class CharN(str):
        def __repr__(self):
            return repr(self[:maxlen])
    CharN.__qualname__ = CharN.__name__ = "Char(%d)"%maxlen
    return CharN

>>> four = Char(1)('41.700000000000003')
>>> four
'4'
>>> int(four)
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    int(four)
ValueError: invalid literal for int() with base 10: '4'

... well, close. Anyway, a string subclass could probably do this by
accident somehow.

ChrisA



More information about the Python-list mailing list