0
# IPython and Jupyter Integration
1
2
Magic commands, code completion, and interactive development features for Jupyter notebooks and IPython environments, including Revise.jl integration for automatic code reloading during interactive development workflows.
3
4
## Capabilities
5
6
### Julia Magic Commands
7
8
IPython magic commands for executing Julia code directly in Jupyter notebooks and IPython shells.
9
10
```python { .api }
11
class JuliaMagics:
12
"""IPython magics for Julia integration in Jupyter notebooks."""
13
14
def julia(self, line: str, cell: str = None):
15
"""
16
Line and cell magic for executing Julia code.
17
18
Line magic usage: %julia code
19
Cell magic usage: %%julia
20
21
Parameters:
22
- line: Julia code for line magic
23
- cell: Julia code for cell magic
24
"""
25
26
# Magic properties for configuration
27
highlight: bool # Enable syntax highlighting
28
completion: bool # Enable code completion
29
redirect_output_streams: bool # Redirect Julia output to notebook
30
revise: bool # Enable Revise.jl integration
31
```
32
33
### Magic Command Setup and Loading
34
35
Load Julia magic commands in IPython and Jupyter environments.
36
37
```python { .api }
38
# Load extension in IPython/Jupyter
39
%load_ext julia.magic
40
41
# Or programmatically
42
from julia.magic import JuliaMagics
43
get_ipython().register_magic_function(JuliaMagics().julia)
44
```
45
46
### Code Completion and Interactive Features
47
48
Enhanced code completion for Julia code in IPython environments.
49
50
```python { .api }
51
class JuliaCompleter:
52
"""Julia code completion provider for IPython."""
53
54
class IPCompleterPatcher:
55
"""Patches IPython completer with Julia support."""
56
57
def patch_ipcompleter():
58
"""Apply Julia completion patches to IPython."""
59
```
60
61
### Revise.jl Integration
62
63
Automatic code reloading for interactive development using Julia's Revise.jl package.
64
65
```python { .api }
66
def enable_revise():
67
"""Enable Revise.jl integration for automatic code reloading."""
68
69
def disable_revise():
70
"""Disable Revise.jl integration."""
71
72
def make_revise_wrapper(revise):
73
"""Create Revise.jl wrapper function."""
74
75
def register_revise_hook(ip):
76
"""Register Revise.jl hook with IPython shell."""
77
```
78
79
### Interactive Shell Integration
80
81
Enhanced IPython shell features for Julia integration.
82
83
```python { .api }
84
class TerminalInteractiveShellPatcher:
85
"""Patches terminal interactive shell for Julia integration."""
86
87
def patch_interactiveshell(ip):
88
"""Apply shell patches for Julia integration."""
89
```
90
91
## Usage Examples
92
93
### Basic Magic Commands
94
95
```python
96
# In a Jupyter notebook cell
97
%load_ext julia.magic
98
99
# Line magic - single line Julia code
100
%julia println("Hello from Julia!")
101
102
# Cell magic - multi-line Julia code
103
%%julia
104
function fibonacci(n)
105
if n <= 2
106
return 1
107
else
108
return fibonacci(n-1) + fibonacci(n-2)
109
end
110
end
111
112
println(fibonacci(10))
113
```
114
115
### Variable Sharing Between Python and Julia
116
117
```python
118
# In Python cell
119
import numpy as np
120
data = np.array([1, 2, 3, 4, 5])
121
122
# Pass Python variable to Julia
123
%julia -i data println("Data from Python: $data")
124
125
# Execute Julia code and get result back
126
%%julia -o result
127
result = sum(data .^ 2)
128
129
# Use result in Python
130
print(f"Sum of squares: {result}")
131
```
132
133
### Configuration and Customization
134
135
```python
136
%load_ext julia.magic
137
138
# Configure magic settings
139
from julia.magic import JuliaMagics
140
magic = JuliaMagics()
141
142
# Enable syntax highlighting
143
magic.highlight = True
144
145
# Enable code completion
146
magic.completion = True
147
148
# Enable output stream redirection
149
magic.redirect_output_streams = True
150
151
# Enable Revise.jl for automatic reloading
152
magic.revise = True
153
```
154
155
### Advanced Interactive Workflows
156
157
```python
158
# Enable Revise.jl for development
159
from julia.ipy.revise import enable_revise
160
enable_revise()
161
162
# Now Julia code changes are automatically reloaded
163
%%julia
164
# Define a function in a .jl file, then modify it
165
# Changes will be automatically detected and reloaded
166
167
include("my_functions.jl")
168
my_function(10)
169
```
170
171
### Integration with Julia Plotting
172
173
```python
174
%load_ext julia.magic
175
176
# Set up Julia plotting in notebook
177
%%julia
178
using Plots
179
gr() # Use GR backend
180
181
# Create plots that display in notebook
182
%%julia
183
x = range(0, 2π, length=100)
184
y = sin.(x)
185
plot(x, y, title="Sine Wave", xlabel="x", ylabel="sin(x)")
186
```
187
188
### Package Management in Notebooks
189
190
```python
191
%%julia
192
# Install Julia packages from notebook
193
using Pkg
194
Pkg.add("DataFrames")
195
Pkg.add("CSV")
196
197
# Use packages immediately
198
using DataFrames, CSV
199
200
# Create and manipulate data
201
df = DataFrame(x=1:10, y=rand(10))
202
println(df)
203
```
204
205
### Error Handling in Magic Commands
206
207
```python
208
try:
209
%julia undefined_function()
210
except Exception as e:
211
print(f"Julia magic error: {e}")
212
213
# Julia errors are displayed with proper formatting
214
%%julia
215
# This will show a nicely formatted Julia stack trace
216
error("Something went wrong!")
217
```
218
219
### Debugging and Development
220
221
```python
222
# Enable debug output for magic commands
223
from julia.core import enable_debug
224
enable_debug()
225
226
# Now magic commands show detailed execution info
227
%%julia
228
println("Debug information will be visible")
229
230
# Check magic configuration
231
%julia println("Magic is working!")
232
```
233
234
## Magic Command Options
235
236
The Julia magic commands support various options for customizing behavior:
237
238
- `-i VARS`: Input variables from Python to Julia
239
- `-o VARS`: Output variables from Julia to Python
240
- `--no-return`: Don't return the last expression value
241
- `--redirect-stderr`: Redirect Julia stderr to notebook
242
- `--no-redirect-stderr`: Don't redirect Julia stderr
243
244
Example usage:
245
246
```python
247
# Input Python variables to Julia
248
data = [1, 2, 3, 4, 5]
249
%julia -i data result = sum(data)
250
251
# Output Julia variables to Python
252
%julia -o result result = 42
253
print(result) # 42 in Python
254
255
# Complex example with multiple variables
256
x, y = 10, 20
257
%%julia -i x,y -o z
258
z = x * y + 100
259
println("Computed z = $z")
260
```