Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix applying @needs_global_scope to cell magics. #11698

Merged
merged 1 commit into from
Apr 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion IPython/core/interactiveshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -2345,7 +2345,7 @@ def run_cell_magic(self, magic_name, line, cell):
magic_arg_s = self.var_expand(line, stack_depth)
kwargs = {}
if getattr(fn, "needs_local_scope", False):
kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
kwargs['local_ns'] = self.user_ns

with self.builtin_trap:
args = (magic_arg_s, cell)
Expand Down
9 changes: 4 additions & 5 deletions IPython/core/magics/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -1127,8 +1127,8 @@ def timeit(self, line='', cell=None, local_ns=None):
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 = {}
conflict_globs = {}
if local_ns and cell is None:
for var_name, var_val in glob.items():
if var_name in local_ns:
conflict_globs[var_name] = var_val
Expand All @@ -1154,9 +1154,8 @@ def timeit(self, line='', cell=None, local_ns=None):
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 conflict_globs:
glob.update(conflict_globs)

if not quiet :
# Check best timing is greater than zero to avoid a
Expand Down
10 changes: 10 additions & 0 deletions IPython/core/tests/test_magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,16 @@ def test_time3():
"run = 0\n"
"run += 1")

def test_time_local_ns():
"""
Test that local_ns is actually global_ns when running a cell magic
"""
ip = get_ipython()
ip.run_cell("%%time\n"
"myvar = 1")
nt.assert_equal(ip.user_ns['myvar'], 1)
del ip.user_ns['myvar']

def test_doctest_mode():
"Toggle doctest_mode twice, it should be a no-op and run without error"
_ip.magic('doctest_mode')
Expand Down