On Sat, Dec 22, 2012 at 12:57 PM, Oscar Benjamin <oscar.j.benja...@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. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor