diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py index 769a062..ef9ae1b 100644 --- a/IPython/core/magics/execution.py +++ b/IPython/core/magics/execution.py @@ -940,7 +940,8 @@ python-profiler package from non-free.""") @skip_doctest @line_cell_magic - def timeit(self, line='', cell=None): + @needs_local_scope + def timeit(self, line='', cell=None, local_ns=None): """Time execution of a Python statement or expression Usage, in line mode: @@ -1074,7 +1075,16 @@ python-profiler package from non-free.""") tc = clock()-t0 ns = {} - exec(code, self.shell.user_ns, ns) + glob = self.shell.user_ns + # handles global vars with same name as local vars. We store them in conflict_globs. + if local_ns is not None: + conflict_globs = {} + for var_name, var_val in glob.items(): + if var_name in local_ns: + conflict_globs[var_name] = var_val + glob.update(local_ns) + + exec(code, glob, ns) timer.inner = ns["inner"] # This is used to check if there is a huge difference between the @@ -1093,6 +1103,11 @@ python-profiler package from non-free.""") worst = max(all_runs) / number timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) + # Restore global vars from conflict_globs + if local_ns is not None: + if len(conflict_globs) > 0: + glob.update(conflict_globs) + if not quiet : # Check best timing is greater than zero to avoid a # ZeroDivisionError.