13
13
nothing.
14
14
"""
15
15
16
+ import re
17
+ import lib2to3 .pytree as pytree
18
+ from lib2to3 .fixer_util import Leaf , Node
16
19
from lib2to3 import fixer_base
17
20
from lib2to3 .fixer_util import syms , does_tree_import
18
21
from libfuturize .fixer_util import (token , future_import , touch_import_top ,
@@ -28,6 +31,19 @@ def match_division(node):
28
31
return node .type == slash and not node .next_sibling .type == slash and \
29
32
not node .prev_sibling .type == slash
30
33
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
+
31
47
32
48
class FixDivisionSafe (fixer_base .BaseFix ):
33
49
# BM_compatible = True
@@ -64,9 +80,14 @@ def transform(self, node, results):
64
80
return
65
81
future_import (u"division" , node )
66
82
67
- touch_import_top (u'past.utils' , u'old_div' , node )
68
83
expr1 , expr2 = results [0 ].clone (), results [1 ].clone ()
69
84
# Strip any leading space for the first number:
70
85
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 )
71
92
return wrap_in_fn_call ("old_div" , (expr1 , expr2 ), prefix = node .prefix )
72
93
0 commit comments