diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 3584efb..ef57255 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -2343,8 +2343,13 @@ class InteractiveShell(SingletonConfigurable): 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): diff --git a/docs/source/config/custommagics.rst b/docs/source/config/custommagics.rst index 8726000..fb8e47c 100644 --- a/docs/source/config/custommagics.rst +++ b/docs/source/config/custommagics.rst @@ -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 ================