0
# Core Julia Runtime
1
2
Primary interface for executing Julia code from Python, providing runtime initialization, module importing, function calling, and automatic type conversion between Python and Julia data structures.
3
4
## Capabilities
5
6
### Julia Runtime Initialization
7
8
Initialize and configure the Julia runtime with various options for optimization, compilation, and system configuration.
9
10
```python { .api }
11
class Julia:
12
def __init__(self, init_julia=True, jl_init_path=None, runtime=None,
13
jl_runtime_path=None, debug=False, **julia_options):
14
"""
15
Create a Python object that represents a live Julia runtime.
16
17
Parameters:
18
- init_julia: bool, whether to initialize Julia runtime (default: True)
19
- jl_init_path: Path to Julia initialization script (deprecated)
20
- runtime: str, custom Julia binary path
21
- jl_runtime_path: Path to Julia runtime (deprecated)
22
- debug: bool, enable debugging information
23
- **julia_options: Additional Julia options including:
24
- sysimage: Path to custom Julia system image
25
- bindir: Julia binary directory path
26
- compiled_modules: Module compilation setting ('yes'/'no')
27
- compile: Compilation level ('yes'/'no'/'all'/'min')
28
- depwarn: Deprecation warnings ('yes'/'no'/'error')
29
- optimize: Optimization level (0/1/2/3)
30
- threads: Number of Julia threads (int or 'auto')
31
- inline: Inline function calls ('yes'/'no')
32
- check_bounds: Array bounds checking ('yes'/'no')
33
- warn_overwrite: Method overwrite warnings ('yes'/'no')
34
- min_optlevel: Minimum optimization level (0/1/2/3)
35
"""
36
37
class LegacyJulia(Julia):
38
"""Legacy wrapper around Julia class for backward compatibility."""
39
```
40
41
### Code Execution
42
43
Execute Julia code and expressions directly from Python with automatic type conversion.
44
45
```python { .api }
46
def eval(self, code: str):
47
"""
48
Evaluate Julia code and return the result.
49
50
Parameters:
51
- code: Julia code string to execute
52
53
Returns:
54
- Result of Julia expression with automatic Python type conversion
55
"""
56
57
def using(self, module_name: str):
58
"""
59
Load a Julia module (equivalent to 'using ModuleName' in Julia).
60
61
Parameters:
62
- module_name: Name of Julia module to load
63
"""
64
```
65
66
### Module Access and Importing
67
68
Access Julia modules directly as Python objects with automatic function and constant exposure.
69
70
```python { .api }
71
class JuliaModule:
72
"""
73
Represents a Julia module accessible from Python.
74
Provides attribute access to Julia functions and constants.
75
"""
76
77
class JuliaMainModule(JuliaModule):
78
"""
79
Special Julia Main module with assignment support.
80
Allows setting Julia variables from Python.
81
"""
82
83
class JuliaImporter:
84
"""Meta path finder for importing Julia modules."""
85
86
class JuliaModuleLoader:
87
"""Loader implementation for Julia modules."""
88
89
# Direct module importing
90
from julia import Base # Julia's Base module
91
from julia import Main # Julia's Main module
92
from julia import Pkg # Julia's package manager
93
```
94
95
### Julia System Information
96
97
Retrieve detailed information about the Julia installation and runtime configuration.
98
99
```python { .api }
100
class JuliaInfo:
101
"""
102
Information required for initializing Julia runtime.
103
Contains paths, version info, and compatibility checks.
104
105
Attributes:
106
- julia: str, path to Julia executable
107
- bindir: str, Julia's Sys.BINDIR path
108
- libjulia_path: str, path to libjulia shared library
109
- sysimage: str, path to Julia system image
110
- python: str, Python executable used by PyCall.jl
111
- libpython_path: str, libpython path used by PyCall.jl
112
- version_info: tuple, Julia version information
113
- version_raw: str, raw Julia version string
114
"""
115
116
@classmethod
117
def load(cls, julia="julia", **popen_kwargs):
118
"""
119
Get basic information from Julia executable.
120
121
Parameters:
122
- julia: str, path to Julia executable (default: "julia")
123
- **popen_kwargs: Additional arguments for subprocess.Popen
124
125
Returns:
126
- JuliaInfo instance with system information
127
"""
128
129
def is_pycall_built(self) -> bool:
130
"""Check if PyCall.jl is properly built."""
131
132
def is_compatible_python(self) -> bool:
133
"""Check if current Python is compatible with PyCall.jl configuration."""
134
```
135
136
### Package Installation and Setup
137
138
Install and configure Julia packages required for PyJulia operation.
139
140
```python { .api }
141
def install(julia="julia", color="auto", python=None, quiet=False):
142
"""
143
Install/configure Julia packages required by PyJulia.
144
145
Parameters:
146
- julia: Path to Julia executable (default: "julia")
147
- color: Color output setting ("auto"/"yes"/"no")
148
- python: Python executable path (default: current Python)
149
- quiet: Suppress output if True
150
"""
151
```
152
153
### Runtime Configuration and Debugging
154
155
Configure logging, debugging, and runtime behavior for troubleshooting and development.
156
157
```python { .api }
158
def enable_debug():
159
"""Enable debug-level logging for troubleshooting."""
160
161
def set_loglevel(level):
162
"""
163
Set PyJulia's logging level.
164
165
Parameters:
166
- level: Logging level (DEBUG/INFO/WARNING/ERROR)
167
"""
168
169
def get_loghandler():
170
"""Get PyJulia's logging StreamHandler instance."""
171
```
172
173
### Revise.jl Integration
174
175
Enable or disable Revise.jl integration for automatic code reloading during development.
176
177
```python { .api }
178
def enable_revise():
179
"""(Re-)enable Revise.jl integration for development workflows."""
180
181
def disable_revise():
182
"""Disable Revise.jl integration for development workflows."""
183
```
184
185
### Name Conversion Utilities
186
187
Convert between Python and Julia identifier naming conventions.
188
189
```python { .api }
190
def jl_name(name: str) -> str:
191
"""
192
Convert Python identifier to Julia identifier.
193
Handles '_b' suffix → '!' conversion.
194
"""
195
196
def py_name(name: str) -> str:
197
"""
198
Convert Julia identifier to Python identifier.
199
Handles '!' → '_b' suffix conversion.
200
"""
201
202
def ismacro(name: str) -> bool:
203
"""Check if name represents a Julia macro."""
204
205
def isoperator(name: str) -> bool:
206
"""Check if name represents a Julia operator."""
207
208
def is_accessible_name(name: str) -> bool:
209
"""Check if Julia name is accessible from Python."""
210
```
211
212
## Usage Examples
213
214
### Basic Julia Execution
215
216
```python
217
from julia import Julia
218
219
# Initialize Julia
220
jl = Julia()
221
222
# Execute Julia code
223
result = jl.eval('2 + 3')
224
print(result) # 5
225
226
# Use Julia's mathematical functions
227
jl.eval('using Statistics')
228
data = jl.eval('[1, 2, 3, 4, 5]')
229
mean_val = jl.eval('mean([1, 2, 3, 4, 5])')
230
print(mean_val) # 3.0
231
```
232
233
### Module Importing and Function Calling
234
235
```python
236
from julia import Base, Main
237
238
# Call Julia Base functions
239
sin_result = Base.sin(3.14159/2)
240
print(sin_result) # ≈1.0
241
242
# Access Julia constants
243
pi_val = Base.pi
244
print(pi_val) # 3.141592653589793
245
246
# Use Main module for custom variables
247
Main.my_var = [1, 2, 3]
248
result = Main.eval('sum(my_var)')
249
print(result) # 6
250
```
251
252
### Advanced Runtime Configuration
253
254
```python
255
from julia import Julia
256
257
# Configure Julia with specific options
258
jl = Julia(
259
sysimage="/path/to/custom.so",
260
threads=4,
261
optimize=2,
262
compiled_modules="yes"
263
)
264
265
# Enable debugging for troubleshooting
266
from julia.core import enable_debug
267
enable_debug()
268
269
# Execute with debugging enabled
270
result = jl.eval('println("Debug mode active")')
271
```
272
273
## Exception Handling
274
275
```python { .api }
276
class JuliaError(Exception):
277
"""
278
Wrapper for Julia exceptions raised during execution.
279
Contains the original Julia error information.
280
"""
281
282
class JuliaNotFound(Exception):
283
"""Raised when Julia executable cannot be found."""
284
285
class UnsupportedPythonError(Exception):
286
"""Raised for unsupported Python configurations."""
287
```
288
289
Example error handling:
290
291
```python
292
from julia import Julia, JuliaError
293
294
jl = Julia()
295
296
try:
297
result = jl.eval('undefined_function()')
298
except JuliaError as e:
299
print(f"Julia error: {e}")
300
# Handle Julia-specific errors
301
except Exception as e:
302
print(f"Other error: {e}")
303
```