Merge pull request #757 from anthrotype/fix-round3-None

[py23] fix inconsistency of built-in round on Python 3.5 if second argument is None
This commit is contained in:
Cosimo Lupo 2016-12-04 10:56:08 +00:00 committed by GitHub
commit f59c3c59ed
2 changed files with 20 additions and 3 deletions

View File

@ -336,8 +336,19 @@ if PY3:
return float(d) return float(d)
# in Python 3, 'round3' is an alias to the built-in 'round' if sys.version_info[:2] >= (3, 6):
# in Python 3.6, 'round3' is an alias to the built-in 'round'
round = round3 = round round = round3 = round
else:
# in Python3 < 3.6 we need work around the inconsistent behavior of
# built-in round(), whereby floats accept a second None argument,
# while integers raise TypeError. See https://bugs.python.org/issue27936
_round = round
def round3(number, ndigits=None):
return _round(number) if ndigits is None else _round(number, ndigits)
round = round3
else: else:
# in Python 2, 'round2' is an alias to the built-in 'round' and # in Python 2, 'round2' is an alias to the built-in 'round' and
@ -349,7 +360,7 @@ else:
Implementation of Python 3 built-in round() function. Implementation of Python 3 built-in round() function.
Rounds a number to a given precision in decimal digits (default Rounds a number to a given precision in decimal digits (default
0 digits). This returns an int when called with one argument, 0 digits). This returns an int when ndigits is omitted or is None,
otherwise the same type as the number. otherwise the same type as the number.
Values are rounded to the closest multiple of 10 to the power minus Values are rounded to the closest multiple of 10 to the power minus

View File

@ -164,6 +164,12 @@ class Round3Test(unittest.TestCase):
# floats should be illegal # floats should be illegal
self.assertRaises(TypeError, round3, 3.14159, 2.0) self.assertRaises(TypeError, round3, 3.14159, 2.0)
# None should be allowed
self.assertEqual(round3(1.0, None), 1)
# the following would raise an error with the built-in Python3.5 round:
# TypeError: 'NoneType' object cannot be interpreted as an integer
self.assertEqual(round3(1, None), 1)
def test_halfway_cases(self): def test_halfway_cases(self):
self.assertAlmostEqual(round3(0.125, 2), 0.12) self.assertAlmostEqual(round3(0.125, 2), 0.12)
self.assertAlmostEqual(round3(0.375, 2), 0.38) self.assertAlmostEqual(round3(0.375, 2), 0.38)