Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion docs/src/juliacall-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions docs/src/juliacall.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
10 changes: 8 additions & 2 deletions pysrc/juliacall/_jlwrap/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
23 changes: 23 additions & 0 deletions pytest/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions src/JlWrap/module.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading