Skip to content

Catch exceptions thrown by repr() when called by the dispatcher #1911

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

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 5 additions & 1 deletion include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,11 @@ class cpp_function : public function {
for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
if (!some_args) some_args = true;
else msg += ", ";
msg += pybind11::repr(args_[ti]);
try {
msg += pybind11::repr(args_[ti]);
} catch (...) {
msg += "<repr raised an exception>";
}
}
if (kwargs_in) {
auto kwargs = reinterpret_borrow<dict>(kwargs_in);
Expand Down
11 changes: 11 additions & 0 deletions tests/test_constants_and_functions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
from pybind11_tests import constants_and_functions as m


Expand Down Expand Up @@ -37,3 +38,13 @@ def test_exception_specifiers():
assert m.f2(53) == 55
assert m.f3(86) == 89
assert m.f4(140) == 144


def test_incompatible_args_and_repr_exception():
"""Checks repr exceptions are handled gracefully by the dispatcher."""
class ReprRaises(object):
def __repr__(self):
raise ValueError("repr")
with pytest.raises(TypeError,
match="Invoked with: <repr raised an exception>"):
m.test_function(ReprRaises())