[Python-Dev] trunc()

Nick Coghlan ncoghlan at gmail.com
Fri Jan 25 16:35:44 CET 2008


Christian Heimes wrote:
> Paul Moore wrote:
>> Suggestion:
>>
>> - int() has to stay in builtins for obvious reasons.
>> - put *all* of trunc, ceil, floor, round into math.
>> - make int(float) an error
> 
> Slightly different suggestion:
>  - define int(float) as int(trunc(float))
> 
> In my humble opinion lots of people expect int(-2.5) == -2 and int(2.5)
> == 2. Or in other words: int(float) chops of the digits after the dot.

FWIW, this approach gets a +1 from me (although I'm -0 on taking round() 
out of builtins - that seems like a pointless incompatibility to me).

Yes, blessing 'trunc' as the default mechanism for converting a 
non-integral number to an integer is somewhat arbitrary, but it's a 
piece of arbitrariness with a very long history behind it.

For that matter, we could even formally define int() as falling back to 
trunc() if there is no direct conversion (i.e. int knows about the type 
natively, or the type provides an __int__ method). That way non-integral 
types could just implement __trunc__ without having to worry about 
adding "__int__ = __trunc__" to the class definition.

We would still have operator.index to identify types which can be 
losslessly converted to a builtin integer.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list