From: Serhiy Storchaka Date: Mon, 26 Jan 2015 10:09:59 +0000 (+0200) Subject: Issue #18518: timeit now rejects statements which can't be compiled outside X-Git-Tag: v3.5.0a1~105 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=c959b0cd3061bdad445f839c13ecb69e86ec0b9c;p=python Issue #18518: timeit now rejects statements which can't be compiled outside a function or a loop (e.g. "return" or "break"). --- c959b0cd3061bdad445f839c13ecb69e86ec0b9c diff --cc Doc/library/timeit.rst index dea1ba7c96,503a705fbc..17588bdc87 --- a/Doc/library/timeit.rst +++ b/Doc/library/timeit.rst @@@ -63,20 -63,9 +63,14 @@@ The module defines three convenience fu Create a :class:`Timer` instance with the given statement, *setup* code and *timer* function and run its :meth:`.timeit` method with *number* executions. + The optional *globals* argument specifies a namespace in which to execute the + code. + .. versionchanged:: 3.5 + The optional *globals* parameter was added. - .. note:: - - Because :meth:`.timeit` is executing *stmt*, placing a return statement - in *stmt* will prevent :meth:`.timeit` from returning execution time. - It will instead return the data specified by your return statement. - -.. function:: repeat(stmt='pass', setup='pass', timer=, repeat=3, number=1000000) + +.. function:: repeat(stmt='pass', setup='pass', timer=, repeat=3, number=1000000, globals=None) Create a :class:`Timer` instance with the given statement, *setup* code and *timer* function and run its :meth:`.repeat` method with the given *repeat* diff --cc Lib/timeit.py index 5971d378ca,9cec000f73..38077941fe --- a/Lib/timeit.py +++ b/Lib/timeit.py @@@ -108,13 -104,17 +108,19 @@@ class Timer multi-line string literals. """ - def __init__(self, stmt="pass", setup="pass", timer=default_timer): + def __init__(self, stmt="pass", setup="pass", timer=default_timer, + globals=None): """Constructor. See class doc string.""" self.timer = timer - ns = {} + local_ns = {} + global_ns = _globals() if globals is None else globals if isinstance(stmt, str): + # Check that the code can be compiled outside a function + if isinstance(setup, str): + 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, str): setup = reindent(setup, 4)