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

extension-system.mddocs/

Extension System

IPython's plugin architecture for loading and managing extensions that add custom functionality, magic commands, hooks, and integrations. Extensions can be loaded dynamically and provide a clean way to extend IPython's capabilities.

Capabilities

Extension Loading and Management

Core functions and classes for managing IPython extensions.

def load_ipython_extension(ipython):
    """
    Extension loading entry point function.
    
    This function must be defined in any module that serves as an IPython
    extension. It receives the current IPython instance and can register
    magic commands, add hooks, or modify IPython behavior.
    
    Parameters:
    - ipython: InteractiveShell instance - Current IPython shell
    """

def unload_ipython_extension(ipython):
    """
    Extension unloading entry point function.
    
    Optional function for cleaning up when an extension is unloaded.
    Should remove any registered magics, hooks, or other modifications.
    
    Parameters:
    - ipython: InteractiveShell instance - Current IPython shell
    """

class ExtensionManager:
    """
    Manager for loading and unloading IPython extensions.
    
    Handles extension discovery, loading, unloading, and tracks
    loaded extensions to prevent conflicts.
    """
    
    def load_extension(self, module_str):
        """
        Load an IPython extension by module name.
        
        Parameters:
        - module_str: str - Python module name of extension
        
        Returns:
        str: 'already loaded', 'no load function', or None for success
        """
    
    def unload_extension(self, module_str):
        """
        Unload an IPython extension by module name.
        
        Parameters:
        - module_str: str - Python module name of extension
        
        Returns:
        str: 'not loaded', 'no unload function', or None for success  
        """
    
    def reload_extension(self, module_str):
        """
        Reload an IPython extension by unloading and loading it.
        
        Parameters:
        - module_str: str - Python module name of extension
        """

Usage example:

# Load extensions using magic commands
%load_ext extension_name
%unload_ext extension_name  
%reload_ext extension_name

# Load extensions programmatically
ipython = get_ipython()
ipython.magic('load_ext myextension')

# Or use the extension manager directly
ipython.extension_manager.load_extension('myextension')

Creating Custom Extensions

Framework and patterns for building IPython extensions.

# Extension module structure (myextension.py)
from IPython.core.magic import magics_class, line_magic, Magics

@magics_class
class MyMagics(Magics):
    
    @line_magic
    def my_command(self, line):
        """Custom magic command: %my_command"""
        print(f"Running my command with: {line}")

def load_ipython_extension(ipython):
    """Load the extension - required function"""
    # Register magic commands
    ipython.register_magic_function(MyMagics(ipython).my_command, 'line', 'my_command')
    
    # Add hooks
    ipython.events.register('pre_execute', pre_execute_hook)
    
    # Modify IPython configuration
    ipython.autoindent = True
    
    print("MyExtension loaded successfully")

def unload_ipython_extension(ipython):
    """Unload the extension - optional function"""
    # Clean up registered items
    del ipython.magics_manager.magics['line']['my_command']
    
    # Remove hooks
    ipython.events.unregister('pre_execute', pre_execute_hook)
    
    print("MyExtension unloaded")

def pre_execute_hook():
    """Example hook function"""
    print("Code is about to execute")

Built-in Extensions

IPython includes several built-in extensions for common functionality.

# autoreload extension - Automatic module reloading
# Usage: %load_ext autoreload
#        %autoreload 2  # Reload all modules automatically

# storemagic extension - Persistent magic storage  
# Usage: %load_ext storemagic
#        %store variable_name  # Store variable persistently
#        %store -r variable_name  # Restore variable

# deduperreload extension - Deduplicating reload functionality
# Usage: %load_ext deduperreload

Built-in extension usage:

# Autoreload - automatically reload changed modules
%load_ext autoreload
%autoreload 2  # Reload all modules before executing code

# Now modules will be automatically reloaded when changed
import mymodule
mymodule.my_function()  # Will use latest version after changes

# Store magic - persist variables between sessions
%load_ext storemagic  
important_data = [1, 2, 3, 4, 5]
%store important_data  # Save for later sessions

# In a new session:
%store -r important_data  # Restore the variable
print(important_data)  # [1, 2, 3, 4, 5]

Extension Development Patterns

Common patterns and utilities for extension development.

# Hook system integration
def setup_hooks(ipython):
    """Setup event hooks for extension"""
    ipython.events.register('pre_execute', my_pre_execute_hook)
    ipython.events.register('post_execute', my_post_execute_hook)
    ipython.events.register('shell_initialized', my_init_hook)

# Configuration integration  
from traitlets import Bool, Unicode, Int
from IPython.core.configurable import Configurable

class MyExtensionConfig(Configurable):
    """Configuration class for extension"""
    enabled = Bool(True, help="Enable extension functionality").tag(config=True)
    custom_option = Unicode('default', help="Custom option").tag(config=True)
    max_items = Int(10, help="Maximum items to process").tag(config=True)

# Magic command with configuration
@magics_class  
class ConfigurableMagics(Magics):
    
    def __init__(self, shell=None, **kwargs):
        super().__init__(shell=shell, **kwargs)
        self.config = MyExtensionConfig(parent=shell)
    
    @line_magic
    def my_magic(self, line):
        """Magic that uses configuration"""
        if not self.config.enabled:
            return "Extension disabled"
        return f"Processing {line} (max: {self.config.max_items})"

Example complete extension:

"""
Example IPython extension: line_profiler_ext.py

Provides %lprun magic for line-by-line profiling
"""
from IPython.core.magic import magics_class, line_cell_magic, Magics
from IPython.core.magic_arguments import magic_arguments, parse_argstring, argument

@magics_class
class LineProfilerMagics(Magics):
    
    @line_cell_magic
    @magic_arguments()
    @argument('-f', '--function', action='append', 
              help='Function to profile (can be used multiple times)')
    @argument('-m', '--module', help='Module to profile')  
    def lprun(self, line, cell=None):
        """
        Line-by-line profiling magic.
        
        Usage:
        %lprun -f func_to_profile code_to_run
        %%lprun -f func_to_profile
        code_to_run
        """
        args = parse_argstring(self.lprun, line)
        
        if cell is None:
            # Line magic mode
            code = line
        else:
            # Cell magic mode  
            code = cell
            
        # Profiling implementation would go here
        print(f"Profiling functions: {args.function}")
        print(f"Code: {code}")

def load_ipython_extension(ipython):
    """Load the line profiler extension"""
    ipython.register_magic_function(LineProfilerMagics, 'line_cell', 'lprun')
    print("Line profiler extension loaded. Use %lprun to profile code.")

def unload_ipython_extension(ipython):
    """Unload the line profiler extension"""  
    del ipython.magics_manager.magics['line']['lprun']
    del ipython.magics_manager.magics['cell']['lprun']
    print("Line profiler extension unloaded.")

Types

class ExtensionManager:
    """
    Manager for IPython extensions.
    
    Tracks loaded extensions and provides methods for loading,
    unloading, and reloading extensions.
    """
    
    def __init__(self, shell=None):
        """Initialize extension manager with shell reference."""
        
    @property  
    def loaded(self):
        """Set of currently loaded extension names."""
    
    def load_extension(self, module_str):
        """Load extension by module name."""
        
    def unload_extension(self, module_str):
        """Unload extension by module name."""
        
    def reload_extension(self, module_str):
        """Reload extension by module name."""

# Event system for extensions
class EventManager:
    """
    Manager for IPython events and hooks.
    
    Allows extensions to register callbacks for various
    IPython events like code execution, shell initialization, etc.
    """
    
    def register(self, event, func):
        """
        Register callback for event.
        
        Parameters:
        - event: str - Event name ('pre_execute', 'post_execute', etc.)
        - func: callable - Callback function
        """
        
    def unregister(self, event, func):
        """
        Unregister callback for event.
        
        Parameters:
        - event: str - Event name
        - func: callable - Callback function to remove
        """
        
    def trigger(self, event, *args, **kwargs):
        """
        Trigger all callbacks for event.
        
        Parameters:
        - event: str - Event name
        - *args, **kwargs: Arguments passed to callbacks
        """

# Available events for hooks:
# - 'pre_execute': Before code execution
# - 'post_execute': After code execution  
# - 'shell_initialized': When shell is initialized
# - 'pre_run_cell': Before running a cell
# - 'post_run_cell': After running a cell

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