]> 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:09:59 +0000 (12:09 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Mon, 26 Jan 2015 10:09:59 +0000 (12:09 +0200)
a function or a loop (e.g. "return" or "break").

1  2 
Doc/library/timeit.rst
Lib/test/test_timeit.py
Lib/timeit.py
Misc/NEWS

index dea1ba7c96912b2fca02fe9b69f1e96769a0a9c4,503a705fbc3898b06fec2eb8d10469624f8067e7..17588bdc87fe682c5a378bfa509be7703383e335
@@@ -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=<default timer>, repeat=3, number=1000000)
 +
 +.. function:: repeat(stmt='pass', setup='pass', timer=<default 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*
Simple merge
diff --cc Lib/timeit.py
index 5971d378caca28e12f382ff504a464a662f35096,9cec000f7397697404d769f0347656178226c1bf..38077941fe89593a53a848b0a768da43f299abbd
@@@ -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)
diff --cc Misc/NEWS
Simple merge