]> granicus.if.org Git - python/commitdiff
Issue #18518: timeit now rejects statements which can't be compiled outside
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 26 Jan 2015 10:08:37 +0000 (12:08 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Mon, 26 Jan 2015 10:08:37 +0000 (12:08 +0200)
a function or a loop (e.g. "return" or "break").

Lib/test/test_timeit.py
Lib/timeit.py
Misc/NEWS

index 8c4499c9ce42c0f00afe4416ab537140059523d1..daba7ff5a7cfb6335576acde71af2e1dc2bddab5 100644 (file)
@@ -73,9 +73,17 @@ class TestTimeit(unittest.TestCase):
 
     def test_timer_invalid_stmt(self):
         self.assertRaises(ValueError, timeit.Timer, stmt=None)
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='return')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='yield')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='break')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='continue')
 
     def test_timer_invalid_setup(self):
         self.assertRaises(ValueError, timeit.Timer, setup=None)
+        self.assertRaises(SyntaxError, timeit.Timer, setup='return')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='yield')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='break')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='continue')
 
     fake_setup = "import timeit; timeit._fake_timer.setup()"
     fake_stmt = "import timeit; timeit._fake_timer.inc()"
index ef246ce7046e37d919c99670a486b6c2873bba27..a8992f8d771f8a1de520521337e269e44ef3004f 100755 (executable)
@@ -123,6 +123,12 @@ class Timer:
         self.timer = timer
         ns = {}
         if isinstance(stmt, basestring):
+            # Check that the code can be compiled outside a function
+            if isinstance(setup, basestring):
+                compile(setup, dummy_src_name, "exec")
+                compile(setup + '\n' + stmt, dummy_src_name, "exec")
+            else:
+                compile(stmt, dummy_src_name, "exec")
             stmt = reindent(stmt, 8)
             if isinstance(setup, basestring):
                 setup = reindent(setup, 4)
index e018689d2c08dccd21c63d6b31aa8899df14a342..fa5acd860ba72434ca5c220890e919fcedbcebca 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -15,6 +15,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #18518: timeit now rejects statements which can't be compiled outside
+  a function or a loop (e.g. "return" or "break").
+
 - Issue #19996: Make :mod:`httplib` ignore headers with no name rather than
   assuming the body has started.