[Python-Dev] functions vs methods (was Re: trunc())

Raymond Hettinger python at rcn.com
Tue Jan 29 00:19:26 CET 2008


> One thing I'm beginning to feel more and more strongly about
> is that round, trunc, ceil and floor all belong in the same
>  category, and either should all be builtins or should all 
> be in math.
>
> I should also admit that the 2-arg version of round() was 
> borrowed from ABC, but the use case for it there doesn't map
> to Python: in ABC it's the only tool you have for floating point
> formatting on output, while in Python the same thing would 
> typically be done with "%.2f" % x rather than round(x, 2).

New idea:

* Drop the existing second argument for round.
* Fold ceil(), floor(), trunc(), and round() into a single function:

   def round(x, mode=):
       if mode==CEIL:
           return math.ceil(x)
       elif mode==FLOOR:
           return math.floor(x)
       elif mode==TRUNC:
           return math.floor(x) if x>0 else math.ceil(x)
       elif mode==ROUND_TO_EVEN:
           . . .

Maybe we don't need a separate function and magic method for every possible rounding mode.

Also, I think there was some discussion of changing round() to use statistician's rounding.  We might as well make it explicit that this is the new default.


Raymond

P.S.  One place to attach the constants is to the function object, so we would write:
   
   x = round(3.1)              # ROUND_TO_EVEN
   x = round(3.1, round.CEIL)
    . . .


More information about the Python-Dev mailing list