nanobind icon indicating copy to clipboard operation
nanobind copied to clipboard

[BUG]: nanobind fails with unhelpful error message when super.__init__ isn't called by overridden constructor

Open virtuald opened this issue 1 month ago • 0 comments

Problem description

pybind11 does this and it's very useful for reminding users to call super().__init__() when inheriting from a bound class. A quick look at nanobind indicates that it's also required and currently nothing performs this check. nanobind doesn't crash (unlike pybind11) but the error is still really difficult to diagnose:

>>> f = Foo()
>>> f.getX()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    f.getX()
    ~~~~~~^^
TypeError: getX(): incompatible function arguments. The following argument types are supported:
    1. getX(self) -> int

If you're open to bringing it over, I can put together a PR at some point in the near future.

From the original pybind11 issue: https://github.com/pybind/pybind11/issues/2103:

My users are high school robotics teams, and the RobotPy project is wrapping a C++ library that uses a lot of inheritance. They keep inheriting from C++ objects, add a constructor without calling the super constructor, it crashes, and they don't really know why at first. It would be great if pybind11 could catch this and throw a python exception instead with a useful error message.

pybind11 PR fixing it (but obviously we'd want to use whatever the latest version is): https://github.com/pybind/pybind11/pull/2152

Reproducible example code

class Foo(SomeNanoBoundClass):
   def __init__(self):
       pass # oops

f = Foo()
f.some_bound_function_that_needs_cpp_instance_data()

virtuald avatar Nov 05 '25 02:11 virtuald