pybind / pybind/pybind11

[BUG]: Issue with Re-registering Exceptions in Multiple Interpreter Lifecycles

Open
#4,967 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

triage
Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Required prerequisites
What version (or hash if on master) of pybind11 are you using?

latest

Problem description

When registering an exception in a PYBIND11_MODULE scope (with pybind11::register_exception), pybind invokes allows this action only once per exception type.
This is due to the usage of gil_safe_call_once_and_store in register_exception_impl.

The issue is, that some programs require to initialize + deinitialize the interpreter multiple times within the program's life time.
So, everytime a module is created, the register_exception occurs, however, after the first time it is invoked, it will never be invoked again for the same exception class due to the usage of gil_safe_call_once_and_store (which calls std::call_once).

A simple solution for this is to not use the call_once in gil_safe_call_once_and_store, and simply registering the exception
whenever a registration is invoked, regardless of it being already invoked previously.

This is pretty simple, makes me wonder if this was intended.

Reproducible example code
// a definition of MyException...

PYBIND11_EMBEDDED_MODULE(sample, m) {
    py::register_exception<MyException>(m, "MyException")
}

int main() {
  py::initialize_interpreter();
  py::exec("from sample import MyException");
  py::finalize_interpreter(); // Here, the exception registration will be destroyed

  py::initialize_interpreter();
  // The following will fail due to ImportError of MyException!
  py::exec("from sample import MyException");
  py::finalize_interpreter();

  return 0;
}
Is this a regression? Put the last known working version here if it is.

Not a regression

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with register_exception_impl and its use of gil_safe_call_once_and_store, then reproduce the two initialize_interpreter/finalize_interpreter cycles shown in the issue. Determine how exception registration is stored across interpreter lifecycles and verify that importing sample.MyException succeeds after the second initialization without breaking existing registration behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.