IPython: Productive Interactive Computing - An advanced interactive computing environment and command shell for Python.
86
Configuration management through profiles, path utilities for IPython directories, system information functions, and various utility classes for IPython development and customization.
Functions for managing IPython directories and locating configuration files.
def get_ipython_dir():
"""
Get the IPython directory path.
Returns the path to the main IPython configuration directory.
Typically ~/.ipython on Unix systems.
Returns:
str: Path to IPython directory
"""
def get_ipython_cache_dir():
"""
Get the IPython cache directory path.
Returns the path to IPython's cache directory for temporary files,
compiled files, and other cached data.
Returns:
str: Path to IPython cache directory
"""
def get_ipython_package_dir():
"""
Get the IPython package installation directory.
Returns the path where the IPython package is installed,
useful for locating built-in resources and extensions.
Returns:
str: Path to IPython package directory
"""
def get_ipython_module_path(module_str):
"""
Get the path to an IPython module.
Parameters:
- module_str: str - Module name (e.g., 'IPython.core.magic')
Returns:
str: Path to module file
"""
def locate_profile(profile='default'):
"""
Find a profile directory by name.
Searches for an IPython profile directory and returns its path.
Creates the profile directory if it doesn't exist.
Parameters:
- profile: str - Profile name (default: 'default')
Returns:
str: Path to profile directory
"""Usage examples:
from IPython.paths import *
# Get IPython directories
ipython_dir = get_ipython_dir()
print(f"IPython config dir: {ipython_dir}")
cache_dir = get_ipython_cache_dir()
print(f"Cache dir: {cache_dir}")
# Locate profile directories
default_profile = locate_profile() # Uses 'default' profile
custom_profile = locate_profile('myprofile')
# Get package paths
package_dir = get_ipython_package_dir()
magic_module = get_ipython_module_path('IPython.core.magic')Functions for gathering system and environment information.
def sys_info():
"""
Get comprehensive system information.
Returns detailed information about the Python environment,
IPython installation, system platform, and dependencies.
Useful for debugging and support requests.
Returns:
dict: System information including:
- IPython version and path
- Python version and executable
- Operating system details
- Key dependency versions
- Environment variables
"""Usage example:
from IPython.utils.sysinfo import sys_info
# Get system information
info = sys_info()
print("System Information:")
for key, value in info.items():
print(f" {key}: {value}")
# Access specific information
print(f"IPython version: {info['ipython_version']}")
print(f"Python executable: {info['sys_executable']}")Utilities for working with Python call frames and extracting context information.
def extract_module_locals(depth=0):
"""
Extract module and local variables from the call stack.
Examines the call stack at the specified depth and extracts
the module and local namespace, useful for embedding and
context-aware operations.
Parameters:
- depth: int - Stack depth to examine (0 = current frame)
Returns:
tuple: (module, locals_dict) where module is the Python module
and locals_dict contains local variables
"""Usage example:
from IPython.utils.frame import extract_module_locals
def my_function():
local_var = "test data"
# Extract current context
module, locals_dict = extract_module_locals(0)
print(f"Module: {module}")
print(f"Local variables: {list(locals_dict.keys())}")
# Extract caller's context
caller_module, caller_locals = extract_module_locals(1)
return module, locals_dict
my_function()Utilities for clipboard integration and data transfer.
def tkinter_clipboard_get():
"""
Get clipboard contents using tkinter.
Returns:
str: Clipboard text content
"""
def osx_clipboard_get():
"""
Get clipboard contents on macOS using pbpaste.
Returns:
str: Clipboard text content
"""
def win32_clipboard_get():
"""
Get clipboard contents on Windows.
Returns:
str: Clipboard text content
"""
def clipboard_get():
"""
Get clipboard contents (cross-platform).
Automatically detects platform and uses appropriate method.
Returns:
str: Clipboard text content
"""Utilities for running background jobs and processes.
class BackgroundJobManager:
"""
Manager for background jobs and processes.
Allows running long-running tasks in the background
while keeping the IPython shell interactive.
"""
def __init__(self):
"""Initialize background job manager."""
def new(self, func_or_code, *args, **kwargs):
"""
Start a new background job.
Parameters:
- func_or_code: callable or str - Function or code to execute
- *args, **kwargs: Arguments for function
Returns:
BackgroundJob: Job object for monitoring
"""
class BackgroundJob:
"""Individual background job."""
def __init__(self, func, *args, **kwargs):
"""Initialize background job."""
def start(self):
"""Start the background job."""
def is_alive(self):
"""Check if job is still running."""
def kill(self):
"""Terminate the background job."""Enhanced data structures for IPython development.
class Struct:
"""
Enhanced dictionary that allows attribute access to items.
A dictionary-like object that supports both dict['key'] and
dict.key access patterns. Useful for configuration objects
and structured data.
"""
def __init__(self, **kwargs):
"""
Initialize Struct with keyword arguments.
Parameters:
- **kwargs: initial key-value pairs
"""
def __getattr__(self, key):
"""Get item as attribute."""
def __setattr__(self, key, value):
"""Set item as attribute."""
def __getitem__(self, key):
"""Get item using dict syntax."""
def __setitem__(self, key, value):
"""Set item using dict syntax."""
def __contains__(self, key):
"""Check if key exists."""
def keys(self):
"""Return keys."""
def values(self):
"""Return values."""
def items(self):
"""Return key-value pairs."""Usage example:
from IPython.utils.ipstruct import Struct
# Create struct with initial data
config = Struct(
debug=True,
max_items=100,
output_format='json'
)
# Access using attribute notation
print(config.debug) # True
config.debug = False
# Access using dict notation
print(config['max_items']) # 100
config['new_option'] = 'value'
# Use like a regular dict
for key, value in config.items():
print(f"{key}: {value}")Advanced pretty printing for complex data structures.
def pretty(obj, verbose=False, max_width=79, newline=True, max_seq_length=1000):
"""
Pretty print an object.
Parameters:
- obj: object to pretty print
- verbose: bool - Include more detail
- max_width: int - Maximum line width
- newline: bool - Add newline at end
- max_seq_length: int - Maximum sequence length to print
Returns:
str: Pretty printed representation
"""
def pprint(obj, verbose=False, max_width=79, newline=True, max_seq_length=1000):
"""
Pretty print and display an object.
Same as pretty() but prints the result instead of returning it.
"""
class PrettyPrinter:
"""
Configurable pretty printer for complex data structures.
Provides fine-grained control over pretty printing behavior,
including custom formatting for specific types.
"""
def __init__(self, output, max_width=79, newline=True, max_seq_length=1000):
"""Initialize pretty printer with output stream."""
def pretty(self, obj):
"""Pretty print object to configured output."""Usage example:
from IPython.lib.pretty import pretty, pprint, PrettyPrinter
import sys
# Simple pretty printing
data = {'users': [{'name': 'Alice', 'scores': [95, 87, 92]},
{'name': 'Bob', 'scores': [78, 82, 88]}]}
print(pretty(data))
pprint(data) # Prints directly
# Custom pretty printer
printer = PrettyPrinter(sys.stdout, max_width=60)
printer.pretty(data)Configuration management for IPython components.
# Base configuration classes use traitlets
from traitlets import Bool, Int, Unicode, List
from IPython.core.configurable import Configurable
class BaseConfig(Configurable):
"""Base configuration class for IPython components."""
enabled = Bool(True, help="Enable this component").tag(config=True)
debug = Bool(False, help="Enable debug mode").tag(config=True)
# Common configuration patterns
class ShellConfig(BaseConfig):
"""Configuration for interactive shell."""
colors = Unicode('Linux', help="Color scheme").tag(config=True)
autoindent = Bool(True, help="Auto-indent code").tag(config=True)
history_length = Int(10000, help="History length").tag(config=True)
class DisplayConfig(BaseConfig):
"""Configuration for display system."""
max_width = Int(79, help="Maximum display width").tag(config=True)
show_repr = Bool(True, help="Show object repr").tag(config=True)class Struct(dict):
"""
Enhanced dictionary with attribute access.
Combines dictionary functionality with attribute access,
making it useful for configuration objects and structured data.
"""
def __init__(self, **kwargs):
"""Initialize with keyword arguments."""
def __getattr__(self, key):
"""Get attribute."""
def __setattr__(self, key, value):
"""Set attribute."""
class PrettyPrinter:
"""
Configurable pretty printer.
Provides advanced pretty printing with customizable formatting
and support for complex nested data structures.
"""
def __init__(self, output, max_width=79, newline=True):
"""Initialize printer with output configuration."""
def pretty(self, obj):
"""Pretty print object."""
# Path and directory types
PathType = str # File system paths
ProfileName = str # IPython profile names
ModulePath = str # Python module pathsInstall with Tessl CLI
npx tessl i tessl/pypi-ipythondocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10