[Python-Dev] trunc() (original) (raw)

Guido van Rossum guido at python.org
Thu Jan 24 19:46:09 CET 2008


On Jan 24, 2008 10:36 AM, Raymond Hettinger <python at rcn.com> wrote:

Can anyone explain to me why we need both trunc() and int()?

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. For float this has been defined the same as trunc() above, but for other types, who knows! int() of a string does something completely different.

Perhaps worse is that sometimes int() is lossy (e.g. with a float input) and sometimes it is not (e.g. with a string input, or with a non-standard representation of integers). There are still some places where a float is accepted incorrectly (silently truncating) due to the use of the int slot. If trunc() had been part of the language from the beginning we wouldn't have needed to introduce index.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list