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

Class Magics

IPython/core/magic.py:480–661  ·  view source on GitHub ↗

Base class for implementing magic functions. Shell functions which can be reached as %function_name. All magic functions should accept a string, which they can parse for their own needs. This can make some functions easier to type, eg `%cd ../` vs. `%cd("../")` Classes providin

Source from the content-addressed store, hash-verified

478
479
480class Magics(Configurable):
481 """Base class for implementing magic functions.
482
483 Shell functions which can be reached as %function_name. All magic
484 functions should accept a string, which they can parse for their own
485 needs. This can make some functions easier to type, eg `%cd ../`
486 vs. `%cd("../")`
487
488 Classes providing magic functions need to subclass this class, and they
489 MUST:
490
491 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
492 individual methods as magic functions, AND
493
494 - Use the class decorator `@magics_class` to ensure that the magic
495 methods are properly registered at the instance level upon instance
496 initialization.
497
498 See :mod:`magic_functions` for examples of actual implementation classes.
499 """
500 # Dict holding all command-line options for each magic.
501 options_table = None
502 # Dict for the mapping of magic names to methods, set by class decorator
503 magics = None
504 # Flag to check that the class decorator was properly applied
505 registered = False
506 # Instance of IPython shell
507 shell = None
508
509 def __init__(self, shell=None, **kwargs):
510 if not(self.__class__.registered):
511 raise ValueError('Magics subclass without registration - '
512 'did you forget to apply @magics_class?')
513 if shell is not None:
514 if hasattr(shell, 'configurables'):
515 shell.configurables.append(self)
516 if hasattr(shell, 'config'):
517 kwargs.setdefault('parent', shell)
518
519 self.shell = shell
520 self.options_table = {}
521 # The method decorators are run when the instance doesn't exist yet, so
522 # they can only record the names of the methods they are supposed to
523 # grab. Only now, that the instance exists, can we create the proper
524 # mapping to bound methods. So we read the info off the original names
525 # table and replace each method name by the actual bound method.
526 # But we mustn't clobber the *class* mapping, in case of multiple instances.
527 class_magics = self.magics
528 self.magics = {}
529 for mtype in magic_kinds:
530 tab = self.magics[mtype] = {}
531 cls_tab = class_magics[mtype]
532 for magic_name, meth_name in cls_tab.items():
533 if isinstance(meth_name, str):
534 # it's a method name, grab it
535 tab[magic_name] = getattr(self, meth_name)
536 else:
537 # it's the real thing

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected