Skip to content

Commit d06d536

Browse files
authored
Fix small bug introduced with PR #4735 (#4845)
* Bug fix: `result[0]` called if `result.empty()` * Add unit test that fails without the fix.
1 parent 8c7b8dd commit d06d536

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

include/pybind11/pybind11.h

+7-5
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,13 @@ inline std::string replace_newlines_and_squash(const char *text) {
5757
std::string result(text);
5858
bool previous_is_whitespace = false;
5959

60-
// Do not modify string representations
61-
char first_char = result[0];
62-
char last_char = result[result.size() - 1];
63-
if (first_char == last_char && first_char == '\'') {
64-
return result;
60+
if (result.size() >= 2) {
61+
// Do not modify string representations
62+
char first_char = result[0];
63+
char last_char = result[result.size() - 1];
64+
if (first_char == last_char && first_char == '\'') {
65+
return result;
66+
}
6567
}
6668
result.clear();
6769

tests/test_kwargs_and_defaults.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
8585
"kw_lb_func7",
8686
[](const std::string &) {},
8787
py::arg("str_arg") = "First line.\n Second line.");
88+
m.def(
89+
"kw_lb_func8", [](const CustomRepr &) {}, py::arg("custom") = CustomRepr(""));
8890

8991
// test_args_and_kwargs
9092
m.def("args_function", [](py::args args) -> py::tuple {

tests/test_kwargs_and_defaults.py

+4
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ def test_function_signatures(doc):
5555
doc(m.kw_lb_func7)
5656
== "kw_lb_func7(str_arg: str = 'First line.\\n Second line.') -> None"
5757
)
58+
assert (
59+
doc(m.kw_lb_func8)
60+
== "kw_lb_func8(custom: m.kwargs_and_defaults.CustomRepr = ) -> None"
61+
)
5862

5963

6064
def test_named_arguments():

0 commit comments

Comments
 (0)