MCPcopy Create free account
hub / github.com/ipython/ipython / _function_magic_marker

Function _function_magic_marker

IPython/core/magic.py:212–265  ·  view source on GitHub ↗

Decorator factory for standalone functions.

(magic_kind)

Source from the content-addressed store, hash-verified

210
211
212def _function_magic_marker(magic_kind):
213 """Decorator factory for standalone functions.
214 """
215 validate_type(magic_kind)
216
217 # This is a closure to capture the magic_kind. We could also use a class,
218 # but it's overkill for just that one bit of state.
219 def magic_deco(arg):
220 call = lambda f, *a, **k: f(*a, **k)
221
222 # Find get_ipython() in the caller's namespace
223 caller = sys._getframe(1)
224 for ns in ['f_locals', 'f_globals', 'f_builtins']:
225 get_ipython = getattr(caller, ns).get('get_ipython')
226 if get_ipython is not None:
227 break
228 else:
229 raise NameError('Decorator can only run in context where '
230 '`get_ipython` exists')
231
232 ip = get_ipython()
233
234 if callable(arg):
235 # "Naked" decorator call (just @foo, no args)
236 func = arg
237 name = func.__name__
238 ip.register_magic_function(func, magic_kind, name)
239 retval = decorator(call, func)
240 elif isinstance(arg, str):
241 # Decorator called with arguments (@foo('bar'))
242 name = arg
243 def mark(func, *a, **kw):
244 ip.register_magic_function(func, magic_kind, name)
245 return decorator(call, func)
246 retval = mark
247 else:
248 raise TypeError("Decorator can only be called with "
249 "string or function")
250 return retval
251
252 # Ensure the resulting decorator has a usable docstring
253 ds = _docstring_template.format('function', magic_kind)
254
255 ds += dedent("""
256 Note: this decorator can only be used in a context where IPython is already
257 active, so that the `get_ipython()` call succeeds. You can therefore use
258 it in your startup files loaded after IPython initializes, but *not* in the
259 IPython configuration file itself, which is executed before IPython is
260 fully up and running. Any file located in the `startup` subdirectory of
261 your configuration profile will be OK in this sense.
262 """)
263
264 magic_deco.__doc__ = ds
265 return magic_deco
266
267
268MAGIC_NO_VAR_EXPAND_ATTR = '_ipython_magic_no_var_expand'

Callers 1

magic.pyFile · 0.85

Calls 3

validate_typeFunction · 0.85
dedentFunction · 0.85
formatMethod · 0.45

Tested by

no test coverage detected