CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ipython

IPython: Productive Interactive Computing - An advanced interactive computing environment and command shell for Python.

86

1.08x
Overview
Eval results
Files

magic-system.mddocs/

Magic System

IPython's extensible command system providing special functionality through % (line) and %% (cell) magic commands. The magic system allows both built-in commands for common tasks and creation of custom magic commands for specialized functionality.

Capabilities

Magic Command Framework

Core decorators and base classes for creating custom magic commands.

@magics_class
class decorator:
    """
    Class decorator to register a class as containing magic functions.
    
    Usage:
    @magics_class
    class MyMagics(Magics):
        # magic methods here
    """

@line_magic  
def decorator(func):
    """
    Decorator to mark a method as a line magic (% commands).
    
    Line magics receive the rest of the line as a single string argument.
    """

@cell_magic
def decorator(func):
    """
    Decorator to mark a method as a cell magic (%% commands).
    
    Cell magics receive the line and the cell content as separate arguments.
    """

@line_cell_magic
def decorator(func):
    """
    Decorator to mark a method as both line and cell magic.
    
    The method receives different arguments based on calling context.
    """

def needs_local_scope(func):
    """
    Decorator for magics that need access to the local namespace.
    
    This is rarely needed and should be used carefully as it can
    impact performance.
    """

@no_var_expand
def decorator(func):
    """
    Decorator to disable variable expansion in magic commands.
    
    Prevents IPython from expanding variables like $var in the
    magic command line before passing to the magic function.
    """

@output_can_be_silenced  
def decorator(func):
    """
    Decorator to mark magic commands that can have output silenced.
    
    Allows the magic to be called with a trailing semicolon
    to suppress output display.
    """

Usage example:

from IPython.core.magic import magics_class, line_magic, cell_magic, Magics

@magics_class
class MyMagics(Magics):
    
    @line_magic
    def hello(self, line):
        """A simple line magic: %hello"""
        print(f"Hello {line}!")
    
    @cell_magic 
    def process(self, line, cell):
        """A simple cell magic: %%process"""
        print(f"Processing with args: {line}")
        print(f"Cell content:\n{cell}")
        
    @line_cell_magic
    def flexible(self, line, cell=None):
        """Works as both %flexible and %%flexible"""
        if cell is None:
            print(f"Line magic: {line}")
        else:
            print(f"Cell magic: {line}, content: {cell}")

# Register the magic class
ipython = get_ipython()
ipython.register_magic_function(MyMagics(ipython).hello, 'line', 'hello')

Magic Arguments Processing

Argument parsing system for magic commands with support for standard command-line argument patterns.

@magic_arguments()
def decorator(func):
    """
    Decorator to enable argument parsing for magic commands.
    
    Must be combined with @argument decorators to define arguments.
    """

@argument(*args, **kwargs)
def decorator(func):
    """
    Decorator to add a command-line argument to a magic function.
    
    Parameters:
    - *args, **kwargs: Passed to argparse.ArgumentParser.add_argument()
    """

@argument_group(name)
def decorator(func):
    """
    Decorator to create an argument group for organizing related arguments.
    
    Parameters:
    - name: str - Name of the argument group
    """

Usage example:

from IPython.core.magic_arguments import magic_arguments, parse_argstring, argument

@magics_class
class ArgumentMagics(Magics):
    
    @line_magic
    @magic_arguments()
    @argument('-n', '--name', default='World', help='Name to greet')
    @argument('-c', '--count', type=int, default=1, help='Number of greetings')
    @argument('--verbose', action='store_true', help='Verbose output')
    def greet(self, line):
        """Magic with argument parsing: %greet -n Alice -c 3 --verbose"""
        args = parse_argstring(self.greet, line)
        
        for i in range(args.count):
            greeting = f"Hello {args.name}!"
            if args.verbose:
                greeting += f" (greeting {i+1})"
            print(greeting)

Built-in Magic Commands

IPython includes numerous built-in magic commands organized into functional groups.

class BasicMagics(Magics):
    """Basic functionality magics (%alias, %which, %reset, etc.)"""

class CodeMagics(Magics):
    """Code execution and editing magics (%edit, %load, %save, %paste, etc.)"""

class ConfigMagics(Magics):
    """Configuration management magics (%config, %profile, etc.)"""

class DisplayMagics(Magics):
    """Display control magics (%page, %pprint, etc.)"""

class ExecutionMagics(Magics):
    """Code execution magics (%run, %timeit, %debug, etc.)"""

class ExtensionMagics(Magics):
    """Extension management magics (%load_ext, %unload_ext, %reload_ext)"""

class HistoryMagics(Magics):
    """Command history magics (%history, %recall, %rerun, etc.)"""

class LoggingMagics(Magics):
    """Logging control magics (%logstart, %logstop, %logstate, etc.)"""

class NamespaceMagics(Magics):
    """Namespace management magics (%who, %whos, %psearch, %del, etc.)"""

class OSMagics(Magics):
    """Operating system interaction magics (%cd, %ls, %mkdir, %cp, etc.)"""

class PackagingMagics(Magics):
    """Package management magics (%pip, %conda)"""

class PylabMagics(Magics):  
    """Matplotlib integration magics (%pylab, %matplotlib)"""

class ScriptMagics(Magics):
    """Script execution magics (%%bash, %%python, %%ruby, etc.)"""

Common built-in magic examples:

# File and code management
%edit filename.py          # Edit file in external editor
%load filename.py           # Load file content into cell
%save filename.py 1-10      # Save lines 1-10 to file
%run script.py              # Execute Python script

# Timing and profiling  
%time code_to_time          # Time single execution
%timeit code_to_benchmark   # Benchmark with multiple runs
%prun code_to_profile       # Profile with line-by-line stats

# System interaction
%ls                         # List directory contents  
%cd /path/to/directory      # Change directory
!command                    # Execute system command

# Variables and namespace
%who                        # List variables
%whos                       # List variables with details
%reset                      # Reset namespace

# History
%history                    # Show command history
%recall n                   # Recall line n from history

# Extensions
%load_ext extension_name    # Load extension
%matplotlib inline          # Enable inline matplotlib

Types

class Magics:
    """
    Base class for creating magic command collections.
    
    All magic classes should inherit from this and use the
    appropriate decorators to mark magic methods.
    """
    
    def __init__(self, shell=None):
        """
        Initialize magic collection.
        
        Parameters:
        - shell: InteractiveShell instance, optional
        """
    
    @property
    def shell(self):
        """Get the current InteractiveShell instance."""

class MagicsManager:
    """
    Manager for magic commands registration and execution.
    
    Handles registration of magic functions and classes,
    manages magic name conflicts, and provides magic execution.
    """
    
    def register_magic_function(self, func, magic_kind='line', magic_name=None):
        """
        Register a standalone function as a magic.
        
        Parameters:
        - func: callable - Function to register
        - magic_kind: str - 'line' or 'cell'  
        - magic_name: str, optional - Name to use (defaults to function name)
        """
    
    def register_magic(self, magic_obj):
        """
        Register a magic object containing magic methods.
        
        Parameters:
        - magic_obj: Magics instance - Object with magic methods
        """

class MagicAlias:
    """
    Alias system for magic commands.
    
    Allows creating aliases for existing magic commands with
    optional parameter pre-filling.
    """
    
    def __init__(self, alias_name, magic_name, magic_kind, magic_params=None):
        """
        Create magic alias.
        
        Parameters:
        - alias_name: str - Name of alias
        - magic_name: str - Target magic name
        - magic_kind: str - Magic type ('line' or 'cell')
        - magic_params: str, optional - Default parameters
        """

Install with Tessl CLI

npx tessl i tessl/pypi-ipython

docs

configuration-utilities.md

core-shell.md

display-system.md

extension-system.md

index.md

magic-system.md

terminal-interface.md

tile.json