Skip to content

Catch missing self argument in overloads constructor #2914

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -555,8 +555,8 @@ class cpp_function : public function {

auto self_value_and_holder = value_and_holder();
if (overloads->is_constructor) {
if (!PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
if (!parent || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid or missing `self` argument");
return nullptr;
}

Expand Down
10 changes: 6 additions & 4 deletions tests/test_factory_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,9 @@ def __init__(self, bad):
# Same as above, but for a class with an alias:
class BrokenTF6(m.TestFactory6):
def __init__(self, bad):
if bad == 1:
if bad == 0:
m.TestFactory6.__init__()
elif bad == 1:
a = m.TestFactory2(tag.pointer, 1)
m.TestFactory6.__init__(a, tag.base, 1)
elif bad == 2:
Expand All @@ -506,13 +508,13 @@ def __init__(self, bad):
BrokenTF1(arg)
assert (
str(excinfo.value)
== "__init__(self, ...) called with invalid `self` argument"
== "__init__(self, ...) called with invalid or missing `self` argument"
)

for arg in (1, 2, 3, 4):
for arg in (0, 1, 2, 3, 4):
with pytest.raises(TypeError) as excinfo:
BrokenTF6(arg)
assert (
str(excinfo.value)
== "__init__(self, ...) called with invalid `self` argument"
== "__init__(self, ...) called with invalid or missing `self` argument"
)