[Python-checkins] r79137 - in sandbox/trunk/2to3/lib2to3: fixes/fix_exitfunc.py tests/test_fixers.py

benjamin.peterson python-checkins at python.org
Sat Mar 20 17:12:54 CET 2010


Author: benjamin.peterson
Date: Sat Mar 20 17:12:53 2010
New Revision: 79137

Log:
add a fixer for setting sys.exitfunc #2356

Added:
   sandbox/trunk/2to3/lib2to3/fixes/fix_exitfunc.py   (contents, props changed)
Modified:
   sandbox/trunk/2to3/lib2to3/tests/test_fixers.py

Added: sandbox/trunk/2to3/lib2to3/fixes/fix_exitfunc.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/2to3/lib2to3/fixes/fix_exitfunc.py	Sat Mar 20 17:12:53 2010
@@ -0,0 +1,70 @@
+"""
+Convert use of sys.exitfunc to use the atexit module.
+"""
+
+# Author: Benjamin Peterson
+
+from lib2to3 import pytree, fixer_base
+from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms
+
+
+class FixExitfunc(fixer_base.BaseFix):
+
+    PATTERN = """
+              (
+                  sys_import=import_name<'import'
+                      ('sys'
+                      |
+                      dotted_as_names< (any ',')* 'sys' (',' any)* >
+                      )
+                  >
+              |
+                  expr_stmt<
+                      power< 'sys' trailer< '.' 'exitfunc' > >
+                  '=' func=any >
+              )
+              """
+
+    def __init__(self, *args):
+        super(FixExitfunc, self).__init__(*args)
+
+    def start_tree(self, tree, filename):
+        super(FixExitfunc, self).start_tree(tree, filename)
+        self.sys_import = None
+
+    def transform(self, node, results):
+        # First, find a the sys import. We'll just hope it's global scope.
+        if "sys_import" in results:
+            if self.sys_import is None:
+                self.sys_import = results["sys_import"]
+            return
+
+        func = results["func"].clone()
+        func.prefix = ""
+        register = pytree.Node(syms.power,
+                               Attr(Name("atexit"), Name("register"))
+                               )
+        call = Call(register, [func], node.prefix)
+        node.replace(call)
+
+        if self.sys_import is None:
+            # That's interesting.
+            self.warning(node, "Can't find sys import; Please add an atexit "
+                             "import at the top of your file.")
+            return
+
+        # Now add an atexit import after the sys import.
+        names = self.sys_import.children[1]
+        if names.type == syms.dotted_as_names:
+            names.append_child(Comma())
+            names.append_child(Name("atexit", " "))
+        else:
+            containing_stmt = self.sys_import.parent
+            position = containing_stmt.children.index(self.sys_import)
+            stmt_container = containing_stmt.parent
+            new_import = pytree.Node("import_name",
+                              [Name("import"), Name("atexit", " ")]
+                              )
+            new = pytree.Node("simple_stmt", [new_import])
+            containing_stmt.insert_child(position + 1, Newline())
+            containing_stmt.insert_child(position + 2, new)

Modified: sandbox/trunk/2to3/lib2to3/tests/test_fixers.py
==============================================================================
--- sandbox/trunk/2to3/lib2to3/tests/test_fixers.py	(original)
+++ sandbox/trunk/2to3/lib2to3/tests/test_fixers.py	Sat Mar 20 17:12:53 2010
@@ -4285,3 +4285,91 @@
     def test_bare_sequenceIncludes(self):
         s = "sequenceIncludes(x, y)"
         self.warns_unchanged(s, "You should use operator.contains here.")
+
+
+class Test_exitfunc(FixerTestCase):
+
+     fixer = "exitfunc"
+
+     def test_simple(self):
+         b = """
+             import sys
+             sys.exitfunc = my_atexit
+             """
+         a = """
+             import sys
+             import atexit
+             atexit.register(my_atexit)
+             """
+         self.check(b, a)
+
+     def test_names_import(self):
+         b = """
+             import sys, crumbs
+             sys.exitfunc = my_func
+             """
+         a = """
+             import sys, crumbs, atexit
+             atexit.register(my_func)
+             """
+         self.check(b, a)
+
+     def test_complex_expression(self):
+         b = """
+             import sys
+             sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
+             """
+         a = """
+             import sys
+             import atexit
+             atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
+             """
+         self.check(b, a)
+
+     def test_comments(self):
+         b = """
+             import sys # Foo
+             sys.exitfunc = f # Blah
+             """
+         a = """
+             import sys
+             import atexit # Foo
+             atexit.register(f) # Blah
+             """
+         self.check(b, a)
+
+         b = """
+             import apples, sys, crumbs, larry # Pleasant comments
+             sys.exitfunc = func
+             """
+         a = """
+             import apples, sys, crumbs, larry, atexit # Pleasant comments
+             atexit.register(func)
+             """
+         self.check(b, a)
+
+     def test_in_a_function(self):
+         b = """
+             import sys
+             def f():
+                 sys.exitfunc = func
+             """
+         a = """
+             import sys
+             import atexit
+             def f():
+                 atexit.register(func)
+              """
+         self.check(b, a)
+
+     def test_no_sys_import(self):
+         b = """sys.exitfunc = f"""
+         a = """atexit.register(f)"""
+         msg = ("Can't find sys import; Please add an atexit import at the "
+             "top of your file.")
+         self.warns(b, a, msg)
+
+
+     def test_unchanged(self):
+         s = """f(sys.exitfunc)"""
+         self.unchanged(s)


More information about the Python-checkins mailing list