Making wrapped modules available in a potentially pre-initialised interpreter #4211
Unanswered
MusicalNinjaDad
asked this question in
Questions
Replies: 2 comments 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
-
I cannot answer your question whether you understand correctly that this should be safe. But I just want to say I encountered the same issue and applied your solution, which seems to work perfectly fine. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
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