Skip to content

Commit d587a2f

Browse files
authored
fix: do not set docstring for function when empty (#2745)
* Do not set docstring for function when it's empty * No need to check pointer for `free` * Use ternary operator to conditionally set `ml_doc`
1 parent 830f8ed commit d587a2f

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

include/pybind11/pybind11.h

+3-3
Original file line numberDiff line numberDiff line change
@@ -439,9 +439,9 @@ class cpp_function : public function {
439439

440440
/* Install docstring */
441441
auto *func = (PyCFunctionObject *) m_ptr;
442-
if (func->m_ml->ml_doc)
443-
std::free(const_cast<char *>(func->m_ml->ml_doc));
444-
func->m_ml->ml_doc = strdup(signatures.c_str());
442+
std::free(const_cast<char *>(func->m_ml->ml_doc));
443+
// Install docstring if it's non-empty (when at least one option is enabled)
444+
func->m_ml->ml_doc = signatures.empty() ? nullptr : strdup(signatures.c_str());
445445

446446
if (rec->is_method) {
447447
m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());

tests/test_docstring_options.cpp

+8
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,14 @@ TEST_SUBMODULE(docstring_options, m) {
4545

4646
m.def("test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring");
4747

48+
{
49+
py::options options;
50+
options.disable_user_defined_docstrings();
51+
options.disable_function_signatures();
52+
53+
m.def("test_function8", []() {});
54+
}
55+
4856
{
4957
py::options options;
5058
options.disable_user_defined_docstrings();

tests/test_docstring_options.py

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ def test_docstring_options():
3434
assert m.test_function7.__doc__.startswith("test_function7(a: int, b: int) -> None")
3535
assert m.test_function7.__doc__.endswith("A custom docstring\n")
3636

37+
# when all options are disabled, no docstring (instead of an empty one) should be generated
38+
assert m.test_function8.__doc__ is None
39+
3740
# Suppression of user-defined docstrings for non-function objects
3841
assert not m.DocstringTestFoo.__doc__
3942
assert not m.DocstringTestFoo.value_prop.__doc__

0 commit comments

Comments
 (0)