pybind / pybind/pybind11

Wrap exception hierarchy across modules

Open
#1,475 0 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hi everyone! I searched quite a bit on the documentation and elsewhere on the Internet, and I didn't find any example on how to wrap a hierarchy of C++ exceptions, including when they span several Python modules. There is the following example in test_exceptions.cpp (see PR #296), but it doesn't seem to be in the documentation, and doesn't span several modules:

auto ex5 = py::register_exception<MyException5>(m, "MyException5");
py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr());

I wasn't quite sure what would be the best practice to get the base PyObject* exception when it is wrapped in another module. I ended up with the following which seems to work:

// In foo/module.cpp
PYBIND11_MODULE(foo, m) {
    py::register_exception<foo::Error>(m, "Error");
}

// In bar/module.cpp
PYBIND11_MODULE(bar, m) {
    py::object base = py::module::import("foo").attr("Error");
    py::register_exception<bar::Error>(m, "Error", base.ptr());
}

// Test
>>> import bar, inspect
>>> inspect.getmro(bar.Error)
(<class 'bar.Error'>, <class 'foo.Error'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>)

Question 1: Does this seems like best practice?

Question 2: If yes, would it make sense to add these two snippets in the documentation? (First example: how to wrap an exception deriving from another wrapped exception; Second example: how to do it when the base exception is wrapped in a different module). I'm happy to help with this and make a pull request if it makes sense.

Thanks!

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 by reviewing the existing hierarchy example in test_exceptions.cpp and the relevant exception-wrapping documentation. Confirm how register_exception uses a base exception from another module, then add the two requested examples if the approach is appropriate. Done means the documentation covers both same-module and cross-module exception hierarchies.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.