Skip to content

Commit abe59a9

Browse files
committed
Do not set docstring for function when it's empty
1 parent 79b0e2c commit abe59a9

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

include/pybind11/pybind11.h

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -439,9 +439,14 @@ class cpp_function : public function {
439439

440440
/* Install docstring */
441441
auto *func = (PyCFunctionObject *) m_ptr;
442-
if (func->m_ml->ml_doc)
442+
// Free and reset previous docstring if it exists
443+
if (func->m_ml->ml_doc) {
443444
std::free(const_cast<char *>(func->m_ml->ml_doc));
444-
func->m_ml->ml_doc = strdup(signatures.c_str());
445+
func->m_ml->ml_doc = nullptr;
446+
}
447+
// Then install new one if it's non-empty (when at least one option is enabled)
448+
if (!signatures.empty())
449+
func->m_ml->ml_doc = strdup(signatures.c_str());
445450

446451
if (rec->is_method) {
447452
m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
@@ -472,7 +477,9 @@ class cpp_function : public function {
472477
arg.value.dec_ref();
473478
}
474479
if (rec->def) {
475-
std::free(const_cast<char *>(rec->def->ml_doc));
480+
if (rec->def->ml_doc) {
481+
std::free(const_cast<char *>(rec->def->ml_doc));
482+
}
476483
// Python 3.9.0 decref's these in the wrong order; rec->def
477484
// If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
478485
// See https://github.com/python/cpython/pull/22670

tests/test_docstring_options.cpp

Lines changed: 8 additions & 0 deletions
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

Lines changed: 3 additions & 0 deletions
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)