Skip to content

Commit 8209539

Browse files
author
Jordan Adler
committed
Skip float divisions in fix_division_safe
1 parent 39a066e commit 8209539

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libfuturize/fixes/fix_division_safe.py

Lines changed: 20 additions & 0 deletions
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,18 @@ 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.]+$')
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+
return expr.children[0].value == u'float'
44+
return False
45+
3146

3247
class FixDivisionSafe(fixer_base.BaseFix):
3348
# BM_compatible = True
@@ -68,5 +83,10 @@ def transform(self, node, results):
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
7191
return wrap_in_fn_call("old_div", (expr1, expr2), prefix=node.prefix)
7292

0 commit comments

Comments
 (0)