Making wrapped modules available in a potentially pre-initialised interpreter #4211
Unanswered
MusicalNinjaDad
asked this question in
Questions
Replies: 1 comment 3 replies
-
Can you use https://docs.rs/pyo3/latest/pyo3/macro.append_to_inittab.html ? |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've been working on testing wrapped functions in rust, without resorting to constantly compiling and installing the python extension module to run tests via pytest.
I hit on snag along the road which forced me to write a little unsafe code and I was hoping that someone with more experience of the workings of pyo3 would be able and willing to take a quick look and let me know your thoughts ...
The problem
When running multiple tests on wrapped modules, interpreter initialisation becomes a problem:
auto-initialize
on then the interpreter is guaranteed to be initialised andappend_to_inittab!()
will fail - in this case all tests are guaranteed to panic.auto-initialize
then there is the risk that the interpreter will already be initialized by a different test - in this case the tests are simply flaky and will panic at random.I experienced this issue continually with different fail points but no easy way to guarantee failure.
The solution I found
This is based on the example in the Guide section 3.4 plus looking through the results of
cargo expand
and the main codebase:I believe that the lifetime of py_adders_pymodule is safe as:
py_adders::__pyo3_init()
is called with the GIL lock in place.'py
lifetime as the rest of the code is using.Bound::from_owned_ptr()
is passed thepy
token from this GIL lock, binding the initialised module to the correct lockand the whole process is performed as a single action.
Have I correctly understood how the GIL lock is handled w.r.t. the lifetime of the PyModule created by
__pyo3_init
?Note:
This sadly also means that compatibility is limited to cPython>=3.9 if I understand make_module correctly.
Thanks for any advice or comments.
Beta Was this translation helpful? Give feedback.
All reactions