diff options
author | Qifan Lu <lqf.1996121@gmail.com> | 2020-12-27 19:56:30 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-12-27 22:56:30 -0500 |
commit | d587a2fd17dc89c0b2d4b6dc7715594bed45fb58 (patch) | |
tree | 2529154fb9406d9f9dc53caf00ca1166a3b3bfbe | |
parent | 830f8eda87fa06614a0328c3fce00060f4135e4c (diff) | |
download | platform_external_python_pybind11-d587a2fd17dc89c0b2d4b6dc7715594bed45fb58.tar.gz platform_external_python_pybind11-d587a2fd17dc89c0b2d4b6dc7715594bed45fb58.tar.bz2 platform_external_python_pybind11-d587a2fd17dc89c0b2d4b6dc7715594bed45fb58.zip |
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`
-rw-r--r-- | include/pybind11/pybind11.h | 6 | ||||
-rw-r--r-- | tests/test_docstring_options.cpp | 8 | ||||
-rw-r--r-- | tests/test_docstring_options.py | 3 |
3 files changed, 14 insertions, 3 deletions
diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index 104f322..70ba635 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -439,9 +439,9 @@ protected: /* Install docstring */ auto *func = (PyCFunctionObject *) m_ptr; - if (func->m_ml->ml_doc) - std::free(const_cast<char *>(func->m_ml->ml_doc)); - func->m_ml->ml_doc = strdup(signatures.c_str()); + std::free(const_cast<char *>(func->m_ml->ml_doc)); + // Install docstring if it's non-empty (when at least one option is enabled) + func->m_ml->ml_doc = signatures.empty() ? nullptr : strdup(signatures.c_str()); if (rec->is_method) { m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr()); diff --git a/tests/test_docstring_options.cpp b/tests/test_docstring_options.cpp index 8c8f79f..8a97af5 100644 --- a/tests/test_docstring_options.cpp +++ b/tests/test_docstring_options.cpp @@ -48,6 +48,14 @@ TEST_SUBMODULE(docstring_options, m) { { py::options options; options.disable_user_defined_docstrings(); + options.disable_function_signatures(); + + m.def("test_function8", []() {}); + } + + { + py::options options; + options.disable_user_defined_docstrings(); struct DocstringTestFoo { int value; diff --git a/tests/test_docstring_options.py b/tests/test_docstring_options.py index 87d80d2..8ee6613 100644 --- a/tests/test_docstring_options.py +++ b/tests/test_docstring_options.py @@ -34,6 +34,9 @@ def test_docstring_options(): assert m.test_function7.__doc__.startswith("test_function7(a: int, b: int) -> None") assert m.test_function7.__doc__.endswith("A custom docstring\n") + # when all options are disabled, no docstring (instead of an empty one) should be generated + assert m.test_function8.__doc__ is None + # Suppression of user-defined docstrings for non-function objects assert not m.DocstringTestFoo.__doc__ assert not m.DocstringTestFoo.value_prop.__doc__ |