From: Serhiy Storchaka Date: Mon, 26 Jan 2015 10:08:37 +0000 (+0200) Subject: Issue #18518: timeit now rejects statements which can't be compiled outside X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=73c086389a81f81d20a9f87eb95cebd15b6ced58;p=python Issue #18518: timeit now rejects statements which can't be compiled outside a function or a loop (e.g. "return" or "break"). --- diff --git a/Lib/test/test_timeit.py b/Lib/test/test_timeit.py index 8c4499c9ce..daba7ff5a7 100644 --- a/Lib/test/test_timeit.py +++ b/Lib/test/test_timeit.py @@ -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()" diff --git a/Lib/timeit.py b/Lib/timeit.py index ef246ce704..a8992f8d77 100755 --- a/Lib/timeit.py +++ b/Lib/timeit.py @@ -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) diff --git a/Misc/NEWS b/Misc/NEWS index e018689d2c..fa5acd860b 100644 --- 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.