How do I future-validate ’round’ functions in Python2?
When round is imported from the future, it behaves differently than the Python3
round
function. Specifically, it does not support negative 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 it be handled? (implicitly, I ask for best practices, most Pythonic, accepted by the community, etc.).
Solution
I’m going to suggest your custom function idea so you can make sure it always does what you want, but this seems like a special (weird) case if I don’t use future.builtin.round()
I get it
python 3.6:
>>> round(4781, -2)
4800
and Python 2.7:
>>> round(4781, -2)
4800.0
It just seems that future.builtins
is corrupted in some way; In this case, you should avoid using the future.builtins.round() function.
Note that py3 round() returns an integer and py2 round()
returns a float, but this seems to be the only difference between the two stock implementations (
for simple rounding operations such as the example given).