[Python-checkins] cpython (2.7): Issue #18518: timeit now rejects statements which can't be compiled outside

serhiy.storchaka python-checkins at python.org
Mon Jan 26 11:15:32 CET 2015


https://hg.python.org/cpython/rev/e8db1cbe416b
changeset:   94303:e8db1cbe416b
branch:      2.7
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Mon Jan 26 12:08:37 2015 +0200
summary:
  Issue #18518: timeit now rejects statements which can't be compiled outside
a function or a loop (e.g. "return" or "break").

files:
  Lib/test/test_timeit.py |  8 ++++++++
  Lib/timeit.py           |  6 ++++++
  Misc/NEWS               |  3 +++
  3 files changed, 17 insertions(+), 0 deletions(-)


diff --git a/Lib/test/test_timeit.py b/Lib/test/test_timeit.py
--- a/Lib/test/test_timeit.py
+++ b/Lib/test/test_timeit.py
@@ -73,9 +73,17 @@
 
     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()"
diff --git a/Lib/timeit.py b/Lib/timeit.py
--- a/Lib/timeit.py
+++ b/Lib/timeit.py
@@ -123,6 +123,12 @@
         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)
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -15,6 +15,9 @@
 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.
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list