test_jit.py: Replace direct `exec` invocation with a wrapper. (#15882)
authorMikhail Zolotukhin <mvz@fb.com>
Thu, 10 Jan 2019 00:57:22 +0000 (16:57 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 10 Jan 2019 01:01:20 +0000 (17:01 -0800)
Summary:
Python2 doesn't allow to invoke `exec` from a nested function:

  File "test/test_jit.py", line 4653
     exec(code, globals(), scope)
  SyntaxError: unqualified exec is not allowed in function 'test' it is a nested function

This patch wraps exec with a separate function, making it work for both python2
and python3.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/15882

Differential Revision: D13614235

Pulled By: ZolotukhinM

fbshipit-source-id: 9a074308c2379f089402e0bf5a996cc649d6dbca

test/test_jit.py

index 5d959bd..6102742 100644 (file)
@@ -2651,6 +2651,11 @@ class TestBatched(TestCase):
                          w_hi, w_hf, w_ho, w_hc, b_i, b_f, b_o, b_c, w_hs, b_s, iter_num_batch, idx_batch)
         self.assertEqual(ys, ybs.examples())
 
+def execWrapper(code, glob, loc):
+    if PY2:
+        exec(code) in glob, loc
+    else:
+        exec(code, glob, loc)
 
 class TestScript(JitTestCase):
     @contextmanager
@@ -4411,7 +4416,7 @@ a")
 
         def run_test(code):
             scope = {}
-            exec(code, globals(), scope)
+            execWrapper(code, globals(), scope)
             cu = torch.jit.CompilationUnit(code)
 
             self.assertEqual(cu.func(), scope['func']())
@@ -4483,7 +4488,7 @@ a")
 
             code = template.format(lhs=args[0], rhs=args[1], op=op)
             scope = {}
-            exec(code, globals(), scope)
+            execWrapper(code, globals(), scope)
             cu = torch.jit.CompilationUnit(code)
             self.assertEqual(cu.func(tensor), scope['func'](tensor))
 
@@ -4617,7 +4622,7 @@ a")
         def test(op, args):
             code = template.format(lhs=args[0], rhs=args[1], op=op)
             scope = {}
-            exec(code, globals(), scope)
+            execWrapper(code, globals(), scope)
             cu = torch.jit.CompilationUnit(code)
             self.assertEqual(
                 cu.func(),
@@ -4644,7 +4649,7 @@ a")
         def test(inp, typ, type_hint):
             code = template.format(typ=typ, type_hint=type_hint)
             scope = {}
-            exec(code, globals(), scope)
+            execWrapper(code, globals(), scope)
             cu = torch.jit.CompilationUnit(code)
             self.assertEqual(
                 cu.func(inp),