0
# Extension System
1
2
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.
3
4
## Capabilities
5
6
### Extension Loading and Management
7
8
Core functions and classes for managing IPython extensions.
9
10
```python { .api }
11
def load_ipython_extension(ipython):
12
"""
13
Extension loading entry point function.
14
15
This function must be defined in any module that serves as an IPython
16
extension. It receives the current IPython instance and can register
17
magic commands, add hooks, or modify IPython behavior.
18
19
Parameters:
20
- ipython: InteractiveShell instance - Current IPython shell
21
"""
22
23
def unload_ipython_extension(ipython):
24
"""
25
Extension unloading entry point function.
26
27
Optional function for cleaning up when an extension is unloaded.
28
Should remove any registered magics, hooks, or other modifications.
29
30
Parameters:
31
- ipython: InteractiveShell instance - Current IPython shell
32
"""
33
34
class ExtensionManager:
35
"""
36
Manager for loading and unloading IPython extensions.
37
38
Handles extension discovery, loading, unloading, and tracks
39
loaded extensions to prevent conflicts.
40
"""
41
42
def load_extension(self, module_str):
43
"""
44
Load an IPython extension by module name.
45
46
Parameters:
47
- module_str: str - Python module name of extension
48
49
Returns:
50
str: 'already loaded', 'no load function', or None for success
51
"""
52
53
def unload_extension(self, module_str):
54
"""
55
Unload an IPython extension by module name.
56
57
Parameters:
58
- module_str: str - Python module name of extension
59
60
Returns:
61
str: 'not loaded', 'no unload function', or None for success
62
"""
63
64
def reload_extension(self, module_str):
65
"""
66
Reload an IPython extension by unloading and loading it.
67
68
Parameters:
69
- module_str: str - Python module name of extension
70
"""
71
```
72
73
Usage example:
74
75
```python
76
# Load extensions using magic commands
77
%load_ext extension_name
78
%unload_ext extension_name
79
%reload_ext extension_name
80
81
# Load extensions programmatically
82
ipython = get_ipython()
83
ipython.magic('load_ext myextension')
84
85
# Or use the extension manager directly
86
ipython.extension_manager.load_extension('myextension')
87
```
88
89
### Creating Custom Extensions
90
91
Framework and patterns for building IPython extensions.
92
93
```python { .api }
94
# Extension module structure (myextension.py)
95
from IPython.core.magic import magics_class, line_magic, Magics
96
97
@magics_class
98
class MyMagics(Magics):
99
100
@line_magic
101
def my_command(self, line):
102
"""Custom magic command: %my_command"""
103
print(f"Running my command with: {line}")
104
105
def load_ipython_extension(ipython):
106
"""Load the extension - required function"""
107
# Register magic commands
108
ipython.register_magic_function(MyMagics(ipython).my_command, 'line', 'my_command')
109
110
# Add hooks
111
ipython.events.register('pre_execute', pre_execute_hook)
112
113
# Modify IPython configuration
114
ipython.autoindent = True
115
116
print("MyExtension loaded successfully")
117
118
def unload_ipython_extension(ipython):
119
"""Unload the extension - optional function"""
120
# Clean up registered items
121
del ipython.magics_manager.magics['line']['my_command']
122
123
# Remove hooks
124
ipython.events.unregister('pre_execute', pre_execute_hook)
125
126
print("MyExtension unloaded")
127
128
def pre_execute_hook():
129
"""Example hook function"""
130
print("Code is about to execute")
131
```
132
133
### Built-in Extensions
134
135
IPython includes several built-in extensions for common functionality.
136
137
```python { .api }
138
# autoreload extension - Automatic module reloading
139
# Usage: %load_ext autoreload
140
# %autoreload 2 # Reload all modules automatically
141
142
# storemagic extension - Persistent magic storage
143
# Usage: %load_ext storemagic
144
# %store variable_name # Store variable persistently
145
# %store -r variable_name # Restore variable
146
147
# deduperreload extension - Deduplicating reload functionality
148
# Usage: %load_ext deduperreload
149
```
150
151
Built-in extension usage:
152
153
```python
154
# Autoreload - automatically reload changed modules
155
%load_ext autoreload
156
%autoreload 2 # Reload all modules before executing code
157
158
# Now modules will be automatically reloaded when changed
159
import mymodule
160
mymodule.my_function() # Will use latest version after changes
161
162
# Store magic - persist variables between sessions
163
%load_ext storemagic
164
important_data = [1, 2, 3, 4, 5]
165
%store important_data # Save for later sessions
166
167
# In a new session:
168
%store -r important_data # Restore the variable
169
print(important_data) # [1, 2, 3, 4, 5]
170
```
171
172
### Extension Development Patterns
173
174
Common patterns and utilities for extension development.
175
176
```python { .api }
177
# Hook system integration
178
def setup_hooks(ipython):
179
"""Setup event hooks for extension"""
180
ipython.events.register('pre_execute', my_pre_execute_hook)
181
ipython.events.register('post_execute', my_post_execute_hook)
182
ipython.events.register('shell_initialized', my_init_hook)
183
184
# Configuration integration
185
from traitlets import Bool, Unicode, Int
186
from IPython.core.configurable import Configurable
187
188
class MyExtensionConfig(Configurable):
189
"""Configuration class for extension"""
190
enabled = Bool(True, help="Enable extension functionality").tag(config=True)
191
custom_option = Unicode('default', help="Custom option").tag(config=True)
192
max_items = Int(10, help="Maximum items to process").tag(config=True)
193
194
# Magic command with configuration
195
@magics_class
196
class ConfigurableMagics(Magics):
197
198
def __init__(self, shell=None, **kwargs):
199
super().__init__(shell=shell, **kwargs)
200
self.config = MyExtensionConfig(parent=shell)
201
202
@line_magic
203
def my_magic(self, line):
204
"""Magic that uses configuration"""
205
if not self.config.enabled:
206
return "Extension disabled"
207
return f"Processing {line} (max: {self.config.max_items})"
208
```
209
210
Example complete extension:
211
212
```python
213
"""
214
Example IPython extension: line_profiler_ext.py
215
216
Provides %lprun magic for line-by-line profiling
217
"""
218
from IPython.core.magic import magics_class, line_cell_magic, Magics
219
from IPython.core.magic_arguments import magic_arguments, parse_argstring, argument
220
221
@magics_class
222
class LineProfilerMagics(Magics):
223
224
@line_cell_magic
225
@magic_arguments()
226
@argument('-f', '--function', action='append',
227
help='Function to profile (can be used multiple times)')
228
@argument('-m', '--module', help='Module to profile')
229
def lprun(self, line, cell=None):
230
"""
231
Line-by-line profiling magic.
232
233
Usage:
234
%lprun -f func_to_profile code_to_run
235
%%lprun -f func_to_profile
236
code_to_run
237
"""
238
args = parse_argstring(self.lprun, line)
239
240
if cell is None:
241
# Line magic mode
242
code = line
243
else:
244
# Cell magic mode
245
code = cell
246
247
# Profiling implementation would go here
248
print(f"Profiling functions: {args.function}")
249
print(f"Code: {code}")
250
251
def load_ipython_extension(ipython):
252
"""Load the line profiler extension"""
253
ipython.register_magic_function(LineProfilerMagics, 'line_cell', 'lprun')
254
print("Line profiler extension loaded. Use %lprun to profile code.")
255
256
def unload_ipython_extension(ipython):
257
"""Unload the line profiler extension"""
258
del ipython.magics_manager.magics['line']['lprun']
259
del ipython.magics_manager.magics['cell']['lprun']
260
print("Line profiler extension unloaded.")
261
```
262
263
## Types
264
265
```python { .api }
266
class ExtensionManager:
267
"""
268
Manager for IPython extensions.
269
270
Tracks loaded extensions and provides methods for loading,
271
unloading, and reloading extensions.
272
"""
273
274
def __init__(self, shell=None):
275
"""Initialize extension manager with shell reference."""
276
277
@property
278
def loaded(self):
279
"""Set of currently loaded extension names."""
280
281
def load_extension(self, module_str):
282
"""Load extension by module name."""
283
284
def unload_extension(self, module_str):
285
"""Unload extension by module name."""
286
287
def reload_extension(self, module_str):
288
"""Reload extension by module name."""
289
290
# Event system for extensions
291
class EventManager:
292
"""
293
Manager for IPython events and hooks.
294
295
Allows extensions to register callbacks for various
296
IPython events like code execution, shell initialization, etc.
297
"""
298
299
def register(self, event, func):
300
"""
301
Register callback for event.
302
303
Parameters:
304
- event: str - Event name ('pre_execute', 'post_execute', etc.)
305
- func: callable - Callback function
306
"""
307
308
def unregister(self, event, func):
309
"""
310
Unregister callback for event.
311
312
Parameters:
313
- event: str - Event name
314
- func: callable - Callback function to remove
315
"""
316
317
def trigger(self, event, *args, **kwargs):
318
"""
319
Trigger all callbacks for event.
320
321
Parameters:
322
- event: str - Event name
323
- *args, **kwargs: Arguments passed to callbacks
324
"""
325
326
# Available events for hooks:
327
# - 'pre_execute': Before code execution
328
# - 'post_execute': After code execution
329
# - 'shell_initialized': When shell is initialized
330
# - 'pre_run_cell': Before running a cell
331
# - 'post_run_cell': After running a cell
332
```