[Python-Dev] trunc()

Jeffrey Yasskin jyasskin at gmail.com
Fri Jan 25 00:14:56 CET 2008


On Jan 24, 2008 1:09 PM, Daniel Stutzbach
<daniel at stutzbachenterprises.com> wrote:
> On Jan 24, 2008 12:46 PM, Guido van Rossum <guido at python.org> wrote:
> > 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!) using whatever rules it likes -- the
> > definition of __int__ is up to whatever the source type likes to do.
>
> What are the use-cases for when trunc() vs int() should be used, and
> for when a class should define __trunc__ vs __int__?

If you intend to convert a real number (usually float, since Decimal
has decided not to support it) to an Integral (usually int), use
whichever of trunc(), round(), math.floor(), or math.ceil() you
intend. In 2.6, that list only includes trunc(). If you absolutely
need an int (the concrete, not duck type) from an Integral or you want
to parse a string, use int().

Real numbers should define __trunc__. Integrals and, perhaps, some
string-like types (maybe an MD5 class?) should define __int__.

At least, that's my suggestion.

-- 
Namasté,
Jeffrey Yasskin


More information about the Python-Dev mailing list