3

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.)

Lee Hachadoorian
  • 364
  • 2
  • 15
  • `from builtins import round` doesn't work for me in Python 2, gives me `ImportError: No module named builtins`. I also can't find it in the documentation. Did you do something special to make that work? If so, what? – Stefan Pochmann Jan 20 '18 at 19:03
  • @StefanPochmann That comes from the future package I assume http://python-future.org/index.html – ayhan Jan 20 '18 at 19:13
  • I did not do anything "special". The statement worked as shown. You could try `from future.builtins import round`. – Lee Hachadoorian Jan 20 '18 at 19:13
  • The most pythonic solution would probably be to drop Python 2... – L3viathan Jan 20 '18 at 20:10

1 Answers1

3

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).

jshrimp29
  • 588
  • 6
  • 8
  • 1
    There are other differences between py2 and py3, such as [Banker's Rounding](http://python-future.org/future-builtins.html). So I don't think I can just *not* import `round` from the future, because I would have to account for several differences to future-proof my code: different return type, as you point out, and different rounding behavior. – Lee Hachadoorian Jan 20 '18 at 19:42
  • Good point. I was referring to just the example given and other simple rounding, but you're absolutely right. I edited my answer to clarify. – jshrimp29 Jan 20 '18 at 19:48