Skip to content

Commit 04a20d3

Browse files
committed
Throw TypeError when subclasses forget to call __init__
- Based on pybind/pybind11#2152 - Fixes #1210
1 parent d145ec5 commit 04a20d3

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

src/nb_type.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1032,6 +1032,14 @@ static PyObject *nb_type_vectorcall(PyObject *self, PyObject *const *args_in,
10321032
return nullptr;
10331033
}
10341034

1035+
if (((nb_inst *)self)->state == nb_inst::state_uninitialized) {
1036+
PyErr_Format(PyExc_TypeError,
1037+
"%.200s.__init__() must be called when overriding __init__",
1038+
td->name);
1039+
Py_DECREF(self);
1040+
return nullptr;
1041+
}
1042+
10351043
// __init__ constructor: 'rv' is None
10361044
Py_DECREF(rv);
10371045
return self;

tests/test_classes.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -256,13 +256,9 @@ def name(self):
256256
def what(self):
257257
return "b"
258258

259-
with pytest.warns(
260-
RuntimeWarning,
261-
match="nanobind: attempted to access an uninitialized instance of type",
262-
):
263-
with pytest.raises(TypeError) as excinfo:
264-
t.go(Incomplete2())
265-
assert "incompatible function arguments" in str(excinfo.value)
259+
with pytest.raises(TypeError) as excinfo:
260+
Incomplete2()
261+
assert "__init__() must be called when overriding __init__" in str(excinfo.value)
266262

267263

268264
def test12_large_pointers():

0 commit comments

Comments
 (0)