diff --git a/CHANGELOG.md b/CHANGELOG.md index 1506de11..56e49e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * Improved TTFX in JuliaCall. * Minimum supported Python version is now 3.11. * JuliaCall option `compiled_modules` now accepts `existing` and `strict` (Julia 1.11+). +* Added the `nogil` keyword to `juliacall.ModuleValue.seval` to evaluate code (such as `using SomePackage`) with the GIL released. ## 0.9.37 (2026-10-12) * Compatibility fix with Python 3.15 from conda-forge, which no longer bundles libpython. diff --git a/docs/src/juliacall-reference.md b/docs/src/juliacall-reference.md index 319da77f..15f1b785 100644 --- a/docs/src/juliacall-reference.md +++ b/docs/src/juliacall-reference.md @@ -184,7 +184,10 @@ This wraps any Julia `Module` value. It is the same as [`AnyValue`](#juliacall.AnyValue) except for one additional convenience method: -- `seval([module=self], code)`: Evaluates the given code (a string) in the given module. +- `seval(code, *, nogil=False)`: Evaluates the given code (a string) in this module. + With `nogil=True`, the GIL is released while the code runs (see + [Multi-threading in the JuliaCall guide](@ref py-multi-threading)). The code must not + interact with Python. ````` `````@customdoc diff --git a/docs/src/juliacall.md b/docs/src/juliacall.md index 11cb9333..ce3350df 100644 --- a/docs/src/juliacall.md +++ b/docs/src/juliacall.md @@ -180,6 +180,20 @@ parallel, taking about 5 seconds in total. If we did not use `_jl_call_nogil` (i.e. if we did `pool.submit(jl.Libc.systemsleep, 5)`) then the above code will take 20 seconds because the sleeps run one after another. +A Python package that loads Julia packages at import time can use `seval(..., nogil=True)` +to load them while another Python thread imports Python modules. This is only safe if +none of the Julia code interacts with Python, including the `__init__` functions of all +the packages it loads. Packages built on PythonCall often call Python in `__init__`. + +```python +import threading +from juliacall import Main as jl +t = threading.Thread(target=lambda: __import__("pandas")) +t.start() +jl.seval("using Statistics", nogil=True) +t.join() +``` + It is very important that any function called with `_jl_call_nogil` does not interact with Python at all unless it re-locks the GIL first, such as by using [`PythonCall.GIL.@lock`](@ref). diff --git a/pysrc/juliacall/_jlwrap/module.py b/pysrc/juliacall/_jlwrap/module.py index 72904247..9492b515 100644 --- a/pysrc/juliacall/_jlwrap/module.py +++ b/pysrc/juliacall/_jlwrap/module.py @@ -12,5 +12,11 @@ class ModuleValue(AnyValue): __slots__ = () def __dir__(self): return ValueBase.__dir__(self) + self._jl_callmethod(_jl_methods["__dir__"]) - def seval(self, expr): - return self._jl_callmethod(_jl_methods["seval"], expr) + def seval(self, expr, *, nogil=False): + '''Evaluate the Julia code `expr` (a string) in this module. + + If `nogil` is true, the GIL is released while the code runs, so other Python + threads can run meanwhile. WARNING: the code must not interact with Python at all + without re-acquiring the GIL. + ''' + return self._jl_callmethod(_jl_methods["seval_nogil" if nogil else "seval"], expr) diff --git a/pytest/test_all.py b/pytest/test_all.py index 8ceaf9df..87ad6db1 100644 --- a/pytest/test_all.py +++ b/pytest/test_all.py @@ -201,6 +201,29 @@ def test_call_nogil(yld, raw): assert 0.9 < t2 < 1.5 +def test_seval_nogil(): + """Tests that seval(..., nogil=True) evaluates code with the GIL released.""" + from concurrent.futures import ThreadPoolExecutor + from time import time + from juliacall import Main as jl, JuliaError + + assert jl.seval("1 + 1", nogil=True) == 2 + # precompile + jl.seval("Libc.systemsleep(0.01)", nogil=True) + # the two sleeps only overlap if the GIL is released while they run + pool = ThreadPoolExecutor(2) + t0 = time() + fs = [pool.submit(jl.seval, "Libc.systemsleep(1)", nogil=True) for _ in range(2)] + for f in fs: + f.result() + t1 = time() - t0 + assert 0.9 < t1 < 1.5 + # errors propagate and the GIL is locked again afterwards + with pytest.raises(JuliaError): + jl.seval('error("boom")', nogil=True) + assert jl.seval("2 + 2", nogil=True) == 4 + + @pytest.mark.parametrize("mode,value", [("existing", 2), ("strict", 3)]) def test_compiled_modules_option(mode, value): import os diff --git a/src/JlWrap/module.jl b/src/JlWrap/module.jl index 9b6ac0f6..0d109b6d 100644 --- a/src/JlWrap/module.jl +++ b/src/JlWrap/module.jl @@ -15,12 +15,21 @@ end # `jl.seval(...)` is often the first call of a JuliaCall session. precompile(pyjlmodule_seval, (Module, Py)) +function pyjlmodule_seval_nogil(self::Module, expr::Py) + code = pyconvert(String, expr) + Py(GIL.@unlock Base.eval(self, Meta.parseall(strip(code)))) +end +# Packages call `jl.seval(..., nogil=True)` at import time, where compiling it would cost +# much of the time it saves. +precompile(pyjlmodule_seval_nogil, (Module, Py)) + function init_module() jl = pyjuliacallmodule m = pyimport("juliacall._jlwrap.module") methods = m._jl_methods methods["__dir__"] = pyjl_methodnum(pyjlmodule_dir) methods["seval"] = pyjl_methodnum(pyjlmodule_seval) + methods["seval_nogil"] = pyjl_methodnum(pyjlmodule_seval_nogil) pycopy!(pyjlmoduletype, jl.ModuleValue) end