Skip to content

Commit cc9452c

Browse files
authored
Merge pull request #345 from jmadler/skipdiv
Skip float divisions in fix_division_safe
2 parents 29477de + ef625b0 commit cc9452c

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/libfuturize/fixes/fix_division_safe.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
nothing.
1414
"""
1515

16+
import re
17+
import lib2to3.pytree as pytree
18+
from lib2to3.fixer_util import Leaf, Node
1619
from lib2to3 import fixer_base
1720
from lib2to3.fixer_util import syms, does_tree_import
1821
from libfuturize.fixer_util import (token, future_import, touch_import_top,
@@ -28,6 +31,19 @@ def match_division(node):
2831
return node.type == slash and not node.next_sibling.type == slash and \
2932
not node.prev_sibling.type == slash
3033

34+
const_re = re.compile('^[0-9]*[.][0-9]*$')
35+
36+
37+
def _is_floaty(expr):
38+
if isinstance(expr, Leaf):
39+
# If it's a leaf, let's see if it's a numeric constant containing a '.'
40+
return const_re.match(expr.value)
41+
elif isinstance(expr, Node):
42+
# If the expression is a node, let's see if it's a direct cast to float
43+
if isinstance(expr.children[0], Leaf):
44+
return expr.children[0].value == u'float'
45+
return False
46+
3147

3248
class FixDivisionSafe(fixer_base.BaseFix):
3349
# BM_compatible = True
@@ -64,9 +80,14 @@ def transform(self, node, results):
6480
return
6581
future_import(u"division", node)
6682

67-
touch_import_top(u'past.utils', u'old_div', node)
6883
expr1, expr2 = results[0].clone(), results[1].clone()
6984
# Strip any leading space for the first number:
7085
expr1.prefix = u''
86+
# if expr1 or expr2 are obviously floats, we don't need to wrap in
87+
# old_div, as the behavior of division between any number and a float
88+
# should be the same in 2 or 3
89+
if _is_floaty(expr1) or _is_floaty(expr2):
90+
return
91+
touch_import_top(u'past.utils', u'old_div', node)
7192
return wrap_in_fn_call("old_div", (expr1, expr2), prefix=node.prefix)
7293

tests/test_future/test_futurize.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1190,7 +1190,7 @@ def test_safe_division(self):
11901190
from __future__ import division
11911191
from past.utils import old_div
11921192
x = old_div(3, 2)
1193-
y = old_div(3., 2)
1193+
y = 3. / 2
11941194
assert x == 1 and isinstance(x, int)
11951195
assert y == 1.5 and isinstance(y, float)
11961196
"""

0 commit comments

Comments
 (0)