0
# Magic System
1
2
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.
3
4
## Capabilities
5
6
### Magic Command Framework
7
8
Core decorators and base classes for creating custom magic commands.
9
10
```python { .api }
11
@magics_class
12
class decorator:
13
"""
14
Class decorator to register a class as containing magic functions.
15
16
Usage:
17
@magics_class
18
class MyMagics(Magics):
19
# magic methods here
20
"""
21
22
@line_magic
23
def decorator(func):
24
"""
25
Decorator to mark a method as a line magic (% commands).
26
27
Line magics receive the rest of the line as a single string argument.
28
"""
29
30
@cell_magic
31
def decorator(func):
32
"""
33
Decorator to mark a method as a cell magic (%% commands).
34
35
Cell magics receive the line and the cell content as separate arguments.
36
"""
37
38
@line_cell_magic
39
def decorator(func):
40
"""
41
Decorator to mark a method as both line and cell magic.
42
43
The method receives different arguments based on calling context.
44
"""
45
46
def needs_local_scope(func):
47
"""
48
Decorator for magics that need access to the local namespace.
49
50
This is rarely needed and should be used carefully as it can
51
impact performance.
52
"""
53
54
@no_var_expand
55
def decorator(func):
56
"""
57
Decorator to disable variable expansion in magic commands.
58
59
Prevents IPython from expanding variables like $var in the
60
magic command line before passing to the magic function.
61
"""
62
63
@output_can_be_silenced
64
def decorator(func):
65
"""
66
Decorator to mark magic commands that can have output silenced.
67
68
Allows the magic to be called with a trailing semicolon
69
to suppress output display.
70
"""
71
```
72
73
Usage example:
74
75
```python
76
from IPython.core.magic import magics_class, line_magic, cell_magic, Magics
77
78
@magics_class
79
class MyMagics(Magics):
80
81
@line_magic
82
def hello(self, line):
83
"""A simple line magic: %hello"""
84
print(f"Hello {line}!")
85
86
@cell_magic
87
def process(self, line, cell):
88
"""A simple cell magic: %%process"""
89
print(f"Processing with args: {line}")
90
print(f"Cell content:\n{cell}")
91
92
@line_cell_magic
93
def flexible(self, line, cell=None):
94
"""Works as both %flexible and %%flexible"""
95
if cell is None:
96
print(f"Line magic: {line}")
97
else:
98
print(f"Cell magic: {line}, content: {cell}")
99
100
# Register the magic class
101
ipython = get_ipython()
102
ipython.register_magic_function(MyMagics(ipython).hello, 'line', 'hello')
103
```
104
105
### Magic Arguments Processing
106
107
Argument parsing system for magic commands with support for standard command-line argument patterns.
108
109
```python { .api }
110
@magic_arguments()
111
def decorator(func):
112
"""
113
Decorator to enable argument parsing for magic commands.
114
115
Must be combined with @argument decorators to define arguments.
116
"""
117
118
@argument(*args, **kwargs)
119
def decorator(func):
120
"""
121
Decorator to add a command-line argument to a magic function.
122
123
Parameters:
124
- *args, **kwargs: Passed to argparse.ArgumentParser.add_argument()
125
"""
126
127
@argument_group(name)
128
def decorator(func):
129
"""
130
Decorator to create an argument group for organizing related arguments.
131
132
Parameters:
133
- name: str - Name of the argument group
134
"""
135
```
136
137
Usage example:
138
139
```python
140
from IPython.core.magic_arguments import magic_arguments, parse_argstring, argument
141
142
@magics_class
143
class ArgumentMagics(Magics):
144
145
@line_magic
146
@magic_arguments()
147
@argument('-n', '--name', default='World', help='Name to greet')
148
@argument('-c', '--count', type=int, default=1, help='Number of greetings')
149
@argument('--verbose', action='store_true', help='Verbose output')
150
def greet(self, line):
151
"""Magic with argument parsing: %greet -n Alice -c 3 --verbose"""
152
args = parse_argstring(self.greet, line)
153
154
for i in range(args.count):
155
greeting = f"Hello {args.name}!"
156
if args.verbose:
157
greeting += f" (greeting {i+1})"
158
print(greeting)
159
```
160
161
### Built-in Magic Commands
162
163
IPython includes numerous built-in magic commands organized into functional groups.
164
165
```python { .api }
166
class BasicMagics(Magics):
167
"""Basic functionality magics (%alias, %which, %reset, etc.)"""
168
169
class CodeMagics(Magics):
170
"""Code execution and editing magics (%edit, %load, %save, %paste, etc.)"""
171
172
class ConfigMagics(Magics):
173
"""Configuration management magics (%config, %profile, etc.)"""
174
175
class DisplayMagics(Magics):
176
"""Display control magics (%page, %pprint, etc.)"""
177
178
class ExecutionMagics(Magics):
179
"""Code execution magics (%run, %timeit, %debug, etc.)"""
180
181
class ExtensionMagics(Magics):
182
"""Extension management magics (%load_ext, %unload_ext, %reload_ext)"""
183
184
class HistoryMagics(Magics):
185
"""Command history magics (%history, %recall, %rerun, etc.)"""
186
187
class LoggingMagics(Magics):
188
"""Logging control magics (%logstart, %logstop, %logstate, etc.)"""
189
190
class NamespaceMagics(Magics):
191
"""Namespace management magics (%who, %whos, %psearch, %del, etc.)"""
192
193
class OSMagics(Magics):
194
"""Operating system interaction magics (%cd, %ls, %mkdir, %cp, etc.)"""
195
196
class PackagingMagics(Magics):
197
"""Package management magics (%pip, %conda)"""
198
199
class PylabMagics(Magics):
200
"""Matplotlib integration magics (%pylab, %matplotlib)"""
201
202
class ScriptMagics(Magics):
203
"""Script execution magics (%%bash, %%python, %%ruby, etc.)"""
204
```
205
206
Common built-in magic examples:
207
208
```python
209
# File and code management
210
%edit filename.py # Edit file in external editor
211
%load filename.py # Load file content into cell
212
%save filename.py 1-10 # Save lines 1-10 to file
213
%run script.py # Execute Python script
214
215
# Timing and profiling
216
%time code_to_time # Time single execution
217
%timeit code_to_benchmark # Benchmark with multiple runs
218
%prun code_to_profile # Profile with line-by-line stats
219
220
# System interaction
221
%ls # List directory contents
222
%cd /path/to/directory # Change directory
223
!command # Execute system command
224
225
# Variables and namespace
226
%who # List variables
227
%whos # List variables with details
228
%reset # Reset namespace
229
230
# History
231
%history # Show command history
232
%recall n # Recall line n from history
233
234
# Extensions
235
%load_ext extension_name # Load extension
236
%matplotlib inline # Enable inline matplotlib
237
```
238
239
## Types
240
241
```python { .api }
242
class Magics:
243
"""
244
Base class for creating magic command collections.
245
246
All magic classes should inherit from this and use the
247
appropriate decorators to mark magic methods.
248
"""
249
250
def __init__(self, shell=None):
251
"""
252
Initialize magic collection.
253
254
Parameters:
255
- shell: InteractiveShell instance, optional
256
"""
257
258
@property
259
def shell(self):
260
"""Get the current InteractiveShell instance."""
261
262
class MagicsManager:
263
"""
264
Manager for magic commands registration and execution.
265
266
Handles registration of magic functions and classes,
267
manages magic name conflicts, and provides magic execution.
268
"""
269
270
def register_magic_function(self, func, magic_kind='line', magic_name=None):
271
"""
272
Register a standalone function as a magic.
273
274
Parameters:
275
- func: callable - Function to register
276
- magic_kind: str - 'line' or 'cell'
277
- magic_name: str, optional - Name to use (defaults to function name)
278
"""
279
280
def register_magic(self, magic_obj):
281
"""
282
Register a magic object containing magic methods.
283
284
Parameters:
285
- magic_obj: Magics instance - Object with magic methods
286
"""
287
288
class MagicAlias:
289
"""
290
Alias system for magic commands.
291
292
Allows creating aliases for existing magic commands with
293
optional parameter pre-filling.
294
"""
295
296
def __init__(self, alias_name, magic_name, magic_kind, magic_params=None):
297
"""
298
Create magic alias.
299
300
Parameters:
301
- alias_name: str - Name of alias
302
- magic_name: str - Target magic name
303
- magic_kind: str - Magic type ('line' or 'cell')
304
- magic_params: str, optional - Default parameters
305
"""
306
```