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

Apply @needs_local_scope to cell magics. #11542

Merged
merged 2 commits into from Mar 12, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion IPython/core/interactiveshell.py
Expand Up @@ -2328,8 +2328,13 @@ def run_cell_magic(self, magic_name, line, cell):
magic_arg_s = line
else:
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

with self.builtin_trap:
result = fn(magic_arg_s, cell)
args = (magic_arg_s, cell)
result = fn(*args, **kwargs)
return result

def find_line_magic(self, magic_name):
Expand Down
12 changes: 12 additions & 0 deletions docs/source/config/custommagics.rst
Expand Up @@ -134,6 +134,18 @@ instantiate the class yourself before registration:
:func:`define_magic` function are advised to adjust their code
for the current API.


Accessing user namespace and local scope
========================================

When creating line magics, you may need to access surrounding scope to get user
variables (e.g when called inside functions). IPython provide the
``@needs_local_scope`` decorator that can be imported from
``IPython.core.magics``. When decorated with ``@needs_local_scope`` a magic will
be passed ``local_ns`` as an argument. As a convenience ``@needs_local_scope``
can also be applied to cell magics even if cell magics cannot appear at local
scope context.

Complete Example
================

Expand Down