Skip to content

Commit b89ee66

Browse files
JuliaCall: add nogil option to seval
`jl.seval(code, nogil=True)` evaluates code with the GIL unlocked, so a package can load its Julia packages while another Python thread imports its Python dependencies. The new method is precompiled, unlike a closure called with `_jl_call_nogil`. Co-authored-by: Miles Cranmer <miles.cranmer@gmail.com>
1 parent 4ed01ff commit b89ee66

6 files changed

Lines changed: 59 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* Improved TTFX in JuliaCall.
66
* Minimum supported Python version is now 3.11.
77
* JuliaCall option `compiled_modules` now accepts `existing` and `strict` (Julia 1.11+).
8+
* Added the `nogil` keyword to `juliacall.ModuleValue.seval` to evaluate code (such as `using SomePackage`) with the GIL released.
89

910
## 0.9.37 (2026-10-12)
1011
* Compatibility fix with Python 3.15 from conda-forge, which no longer bundles libpython.

‎docs/src/juliacall-reference.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,10 @@ This wraps any Julia `Module` value.
184184
185185
It is the same as [`AnyValue`](#juliacall.AnyValue) except for one additional convenience
186186
method:
187-
- `seval([module=self], code)`: Evaluates the given code (a string) in the given module.
187+
- `seval(code, *, nogil=False)`: Evaluates the given code (a string) in this module.
188+
With `nogil=True`, the GIL is released while the code runs (see
189+
[Multi-threading in the JuliaCall guide](@ref py-multi-threading)). The code must not
190+
interact with Python.
188191
`````
189192

190193
`````@customdoc

‎docs/src/juliacall.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,20 @@ parallel, taking about 5 seconds in total.
180180
If we did not use `_jl_call_nogil` (i.e. if we did `pool.submit(jl.Libc.systemsleep, 5)`)
181181
then the above code will take 20 seconds because the sleeps run one after another.
182182

183+
A Python package that loads Julia packages at import time can use `seval(..., nogil=True)`
184+
to load them while another Python thread imports Python modules. This is only safe if
185+
none of the Julia code interacts with Python, including the `__init__` functions of all
186+
the packages it loads. Packages built on PythonCall often call Python in `__init__`.
187+
188+
```python
189+
import threading
190+
from juliacall import Main as jl
191+
t = threading.Thread(target=lambda: __import__("pandas"))
192+
t.start()
193+
jl.seval("using Statistics", nogil=True)
194+
t.join()
195+
```
196+
183197
It is very important that any function called with `_jl_call_nogil` does not interact
184198
with Python at all unless it re-locks the GIL first, such as by using
185199
[`PythonCall.GIL.@lock`](@ref).

‎pysrc/juliacall/_jlwrap/module.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,11 @@ class ModuleValue(AnyValue):
1212
__slots__ = ()
1313
def __dir__(self):
1414
return ValueBase.__dir__(self) + self._jl_callmethod(_jl_methods["__dir__"])
15-
def seval(self, expr):
16-
return self._jl_callmethod(_jl_methods["seval"], expr)
15+
def seval(self, expr, *, nogil=False):
16+
'''Evaluate the Julia code `expr` (a string) in this module.
17+
18+
If `nogil` is true, the GIL is released while the code runs, so other Python
19+
threads can run meanwhile. WARNING: the code must not interact with Python at all
20+
without re-acquiring the GIL.
21+
'''
22+
return self._jl_callmethod(_jl_methods["seval_nogil" if nogil else "seval"], expr)

‎pytest/test_all.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,29 @@ def test_call_nogil(yld, raw):
201201
assert 0.9 < t2 < 1.5
202202

203203

204+
def test_seval_nogil():
205+
"""Tests that seval(..., nogil=True) evaluates code with the GIL released."""
206+
from concurrent.futures import ThreadPoolExecutor
207+
from time import time
208+
from juliacall import Main as jl, JuliaError
209+
210+
assert jl.seval("1 + 1", nogil=True) == 2
211+
# precompile
212+
jl.seval("Libc.systemsleep(0.01)", nogil=True)
213+
# the two sleeps only overlap if the GIL is released while they run
214+
pool = ThreadPoolExecutor(2)
215+
t0 = time()
216+
fs = [pool.submit(jl.seval, "Libc.systemsleep(1)", nogil=True) for _ in range(2)]
217+
for f in fs:
218+
f.result()
219+
t1 = time() - t0
220+
assert 0.9 < t1 < 1.5
221+
# errors propagate and the GIL is locked again afterwards
222+
with pytest.raises(JuliaError):
223+
jl.seval('error("boom")', nogil=True)
224+
assert jl.seval("2 + 2", nogil=True) == 4
225+
226+
204227
@pytest.mark.parametrize("mode,value", [("existing", 2), ("strict", 3)])
205228
def test_compiled_modules_option(mode, value):
206229
import os

‎src/JlWrap/module.jl‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,21 @@ end
1515
# `jl.seval(...)` is often the first call of a JuliaCall session.
1616
precompile(pyjlmodule_seval, (Module, Py))
1717

18+
function pyjlmodule_seval_nogil(self::Module, expr::Py)
19+
code = pyconvert(String, expr)
20+
Py(GIL.@unlock Base.eval(self, Meta.parseall(strip(code))))
21+
end
22+
# Packages call `jl.seval(..., nogil=True)` at import time, where compiling it would cost
23+
# much of the time it saves.
24+
precompile(pyjlmodule_seval_nogil, (Module, Py))
25+
1826
function init_module()
1927
jl = pyjuliacallmodule
2028
m = pyimport("juliacall._jlwrap.module")
2129
methods = m._jl_methods
2230
methods["__dir__"] = pyjl_methodnum(pyjlmodule_dir)
2331
methods["seval"] = pyjl_methodnum(pyjlmodule_seval)
32+
methods["seval_nogil"] = pyjl_methodnum(pyjlmodule_seval_nogil)
2433
pycopy!(pyjlmoduletype, jl.ModuleValue)
2534
end
2635

0 commit comments

Comments
 (0)