OLD | NEW |
(Empty) | |
| 1 """ |
| 2 For the ``future`` package. |
| 3 |
| 4 Adds this import line: |
| 5 |
| 6 from __future__ import division |
| 7 |
| 8 at the top and changes any old-style divisions to be calls to |
| 9 past.utils.old_div so the code runs as before on Py2.6/2.7 and has the same |
| 10 behaviour on Py3. |
| 11 |
| 12 If "from __future__ import division" is already in effect, this fixer does |
| 13 nothing. |
| 14 """ |
| 15 |
| 16 from lib2to3 import fixer_base |
| 17 from lib2to3.fixer_util import syms, does_tree_import |
| 18 from libfuturize.fixer_util import (token, future_import, touch_import_top, |
| 19 wrap_in_fn_call) |
| 20 |
| 21 |
| 22 def match_division(node): |
| 23 u""" |
| 24 __future__.division redefines the meaning of a single slash for division, |
| 25 so we match that and only that. |
| 26 """ |
| 27 slash = token.SLASH |
| 28 return node.type == slash and not node.next_sibling.type == slash and \ |
| 29 not node.prev_sibling.type == slash |
| 30 |
| 31 |
| 32 class FixDivisionSafe(fixer_base.BaseFix): |
| 33 # BM_compatible = True |
| 34 run_order = 4 # this seems to be ignored? |
| 35 |
| 36 _accept_type = token.SLASH |
| 37 |
| 38 PATTERN = """ |
| 39 term<(not('/') any)+ '/' ((not('/') any))> |
| 40 """ |
| 41 |
| 42 def start_tree(self, tree, name): |
| 43 """ |
| 44 Skip this fixer if "__future__.division" is already imported. |
| 45 """ |
| 46 super(FixDivisionSafe, self).start_tree(tree, name) |
| 47 self.skip = "division" in tree.future_features |
| 48 |
| 49 def match(self, node): |
| 50 u""" |
| 51 Since the tree needs to be fixed once and only once if and only if it |
| 52 matches, we can start discarding matches after the first. |
| 53 """ |
| 54 if (node.type == self.syms.term and |
| 55 len(node.children) == 3 and |
| 56 match_division(node.children[1])): |
| 57 expr1, expr2 = node.children[0], node.children[2] |
| 58 return expr1, expr2 |
| 59 else: |
| 60 return False |
| 61 |
| 62 def transform(self, node, results): |
| 63 if self.skip: |
| 64 return |
| 65 future_import(u"division", node) |
| 66 |
| 67 touch_import_top(u'past.utils', u'old_div', node) |
| 68 expr1, expr2 = results[0].clone(), results[1].clone() |
| 69 # Strip any leading space for the first number: |
| 70 expr1.prefix = u'' |
| 71 return wrap_in_fn_call("old_div", (expr1, expr2), prefix=node.prefix) |
| 72 |
OLD | NEW |