[Python-Dev] trunc()

Raymond Hettinger python at rcn.com
Sat Jan 26 08:21:11 CET 2008


> trunc() has well-defined semantics -- it takes a Real instance and
> converts it to an Integer instance using round-towards-zero semantics.
> 
> int() has undefined semantics -- it takes any object and converts it
> to an int (a concrete type!) 

So, the problem is basically this:

       Since int(o) must return an int, you're precluded from defining
       a new Real class with an __int__()  method that returns an instance
       of some new Integral class that isn't an int.

And the proposed solution is:

       Introduce trunc(o) which calls o.__trunc__() which can return
       any Integral type.  And, client code must use trunc() instead of
       int(); otherwise, the two new numeric types won't be exercised.

Is that basically what trunc() is all about -- a variant of int() that can
return something other than an int type -- something that behaves
just like the new math.floor() for positive numbers and math.ceil()
for negative numbers?

If so, I think we would be *much* better-off leaving trunc() out 
entirely and seeing if any use cases arise that aren't handled by
math.floor() and math.ceil() with their precise semantics, 
unambigous naming, and ability to handle generic Reals and Integrals.

The existence of trunc() clashes so severely with existence of int(),
that we need to be damned sure that there are real-world, worthwhile
problems that are not readily solved with floor() and ceil() for rounding
Reals into Integrals or with int() for making ints from the non-fractional
portion of a float.


Raymond















     


More information about the Python-Dev mailing list