Skip to content

Commit

Permalink
Py3: round compatible with py2
Browse files Browse the repository at this point in the history
Python 3 and Python 2 uses different rounding strategies in round().
Function round_py2_compat() do rounding in py2 compatible strategy for both py2 and py3
  • Loading branch information
MartinBasti committed Jul 2, 2016
1 parent d1d2862 commit 0be914f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
18 changes: 17 additions & 1 deletion dns/_compat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys

import decimal
from decimal import Context

if sys.version_info > (3,):
long = int
Expand Down Expand Up @@ -29,3 +30,18 @@ def maybe_decode(x):
return x
def maybe_encode(x):
return x


def round_py2_compat(what):
"""
Python 2 and Python 3 use different rounding strategies in round(). This
function ensures that results are python2/3 compatible and backward
compatible with previous py2 releases
:param what: float
:return: rounded long
"""
d = Context(
prec=len(str(long(what))), # round to integer with max precision
rounding=decimal.ROUND_HALF_UP
).create_decimal(str(what)) # str(): python 2.6 compat
return long(d)
4 changes: 2 additions & 2 deletions dns/rdtypes/ANY/LOC.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import dns.exception
import dns.rdata
from dns._compat import long, xrange
from dns._compat import long, xrange, round_py2_compat


_pows = tuple(long(10**i) for i in range(0, 11))
Expand Down Expand Up @@ -49,7 +49,7 @@ def _float_to_tuple(what):
what *= -1
else:
sign = 1
what = long(round(what * 3600000))
what = round_py2_compat(what * 3600000)
degrees = int(what // 3600000)
what -= degrees * 3600000
minutes = int(what // 60000)
Expand Down
1 change: 0 additions & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ disable=
no-member,
protected-access,
redefined-builtin,
round-builtin,
too-many-lines,
unused-argument,
unused-variable,
Expand Down

0 comments on commit 0be914f

Please sign in to comment.