[Tutor] Limitation of int() in converting strings
eryksun
eryksun at gmail.com
Mon Dec 24 05:42:39 CET 2012
On Sat, Dec 22, 2012 at 12:57 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>>>
>>> def make_int(obj):
>>> '''Coerce str, float and int to int without rounding error
>>> Accepts strings like '4.0' but not '4.1'
>>> '''
>>> fnum = float('%s' % obj)
>>> inum = int(fnum)
>>> assert inum == fnum
>>> return inum
>>
>> Well, that function is dangerously wrong. In no particular order,
>> I can find four bugs and one design flaw.
>
> I expected someone to object to this function. I had hoped that they
> might also offer an improved version, though. I can't see a good way
> to do this without special casing the treatment of some or other type
> (the obvious one being str).
Strings don't implement __int__ or __trunc__; they aren't numbers, so
why not special case them? You can parse strings with obj =
Decimal(obj) (this uses a regex). Then for all inputs set inum =
int(obj) and raise ValueError if inum != obj.
More information about the Tutor
mailing list