Commits

Anonymous committed 21d4d70

Adding absolute import coverage from awkwardduet

  • Participants
  • Parent commits dfc8d2d

Comments (0)

Files changed (2)

File lib3to2/fixes/fix_absimport.py

+'''
+Add 'from __future__ import absolute_import' to any file
+that uses imports.
+'''
+from lib2to3 import fixer_base
+from lib2to3.pygram import python_symbols as syms
+from lib3to2.fixer_util import future_import
+
+class FixAbsimport(fixer_base.BaseFix):
+    order = 'post'
+    
+    def __init__(self, options, log):
+        super(FixAbsimport, self).__init__(options, log)
+        self.__abs_added = None
+        
+    def start_tree(self, tree, filename):
+        super(FixAbsimport, self).start_tree(tree, filename)
+        self.__abs_added = False
+        
+    def match(self, node):
+        return (node.type in (syms.import_name, syms.import_from) 
+                and not self.__abs_added)
+    
+    def transform(self, node, results):
+        future_import('absolute_import', node)
+        self.__abs_added = True
+        
+    def finish_tree(self, tree, filename):
+        fixer_base.BaseFix.finish_tree(self, tree, filename)

File lib3to2/tests/test_absimport.py

+from lib3to2.tests.support import lib3to2FixerTestCase
+
+class Test_absimport(lib3to2FixerTestCase):
+    fixer = 'absimport'
+  
+    def test_import(self):
+      a = 'import abc'
+      b = 'from __future__ import absolute_import\nimport abc'
+      
+      self.check(a, b)
+      
+    def test_no_imports(self):
+      a  = '2+2'
+      
+      self.unchanged(a)