Commit d587a2fd by Qifan Lu Committed by GitHub

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`
parent 830f8eda
...@@ -439,9 +439,9 @@ protected: ...@@ -439,9 +439,9 @@ protected:
/* Install docstring */ /* Install docstring */
auto *func = (PyCFunctionObject *) m_ptr; auto *func = (PyCFunctionObject *) m_ptr;
if (func->m_ml->ml_doc) std::free(const_cast<char *>(func->m_ml->ml_doc));
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 = strdup(signatures.c_str()); func->m_ml->ml_doc = signatures.empty() ? nullptr : strdup(signatures.c_str());
if (rec->is_method) { if (rec->is_method) {
m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr()); m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
......
...@@ -48,6 +48,14 @@ TEST_SUBMODULE(docstring_options, m) { ...@@ -48,6 +48,14 @@ TEST_SUBMODULE(docstring_options, m) {
{ {
py::options options; py::options options;
options.disable_user_defined_docstrings(); options.disable_user_defined_docstrings();
options.disable_function_signatures();
m.def("test_function8", []() {});
}
{
py::options options;
options.disable_user_defined_docstrings();
struct DocstringTestFoo { struct DocstringTestFoo {
int value; int value;
......
...@@ -34,6 +34,9 @@ def test_docstring_options(): ...@@ -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__.startswith("test_function7(a: int, b: int) -> None")
assert m.test_function7.__doc__.endswith("A custom docstring\n") 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 # Suppression of user-defined docstrings for non-function objects
assert not m.DocstringTestFoo.__doc__ assert not m.DocstringTestFoo.__doc__
assert not m.DocstringTestFoo.value_prop.__doc__ assert not m.DocstringTestFoo.value_prop.__doc__
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment