How can I future-proof the `round` function in Python2?

798 views Asked by At

When round is imported from the future, it does not behave the same as the Python3 round function. Specifically, it does not support negative digit rounding.

In Python3:

>>> round(4781, -2)
4800

In Python2:

>>> from builtins import round
>>> round(4781, -2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/future/builtins/newround.py", line 33, in newround
    raise NotImplementedError('negative ndigits not supported yet')
NotImplementedError: negative ndigits not supported yet

Possible solutions include error handling for negative rounding, writing my own round function, etc. How should this be handled? (Implicitly, I'm asking for best practices, most Pythonic, accepted by community, etc.)

1

There are 1 answers

2
jshrimp29 On

I was going to suggest your custom function idea so you can ensure it always does what you want, but this appears to be a special (weird) case where if I don't use future.builtin.round() I get

Python 3.6:

>>> round(4781, -2)
4800

and Python 2.7:

>>> round(4781, -2)
4800.0

It appears to just be the future.builtins that is somehow broken; in this case, you should avoid using the future.builtins.round() function. Note that py3 round() returns an integer while py2 round() returns a float, but that seems to be the only difference between the two stock implementations (for simple rounding operations such as the examples given).