[Python-Dev] trunc()

Michael Urman murman at gmail.com
Sun Jan 27 19:39:35 CET 2008


Is this a valid summary of the arguments so far?

I see two arguments for the change:

  1) The semantics of trunc() are clear: it maps R -> Z in a specific fashion
  2) The semantics of int() are fuzzy; even non-numeric types
(strings) are handled

Yet there will be a __trunc__ that will allow any chosen mapping to be
implemented, so long as it results in an integer, so (1) is only
guaranteed true for the builtin types. This leaves us with (2) which
seems strongly tied to string parsing (as __index__ resolved the other
common X -> integer case).

I see one main argument against:

  *) trunc() results in duplication at best, zealous deprecation at worst

Given that the deprecation or removal of int(2.3) has been dropped,
the argument is about pointless duplication.


What problem is trunc() supposed to solve if it does to floats what
int() does now? I've done some initial code searches for: lang:python
"int(", and I've seen three primary uses for calling int(x):

  a) parsing strings, such as from a user, a config file, or other
serialized format
  b) limiting the input to a function to an integer, such as in a
calendar trying to ensure it has integer months
  c) truncation, such as throwing away sub-seconds from time.time(),
or ensuring integer results from division

It's unclear to me whether (b) could be better served by more
type-specific operations that would prevent passing in strings, or
whether uses like (c) often have latent bugs due to truncation instead
of rounding.

If trunc() is to clarify round vs. integer-portion, it's something
people learn -- the general lack of comments in (c) usages indicates
nobody considers it special behavior. If it's to clarify the
argument's type (the parsing of strings vs. getting integers from
other numeric types), would separating parsing from the int (and
float) constructors also solve this?

Is the aim to "clean up" the following fake example? (Real world uses
of map(int, ...) seem almost uniformly related to string parsing.)

>>> map(int, ("42", 6.022, 2**32))
[42, 6, 4294967296L]

-- 
Michael Urman


More information about the Python-Dev mailing list