Skip to content

[BUG] "__doc__" attribute of static method is not set. #2403

@pkerichang

Description

@pkerichang

The staticmethod wrapper class makes pybind11-generated static methods behave similarly to Python's static methods, which is a great improvement. However, for some reason the docstring of the underlying function is not passed to the staticmethod.

To reproduce, simply define a static method with any docstring (such as "Hello World!"), build the pybind11 library and import in python, then you'll see the docstring is no longer there when you call the help() method on the static method object.

After some trial and error, modifying the def_static() method in pybind11.h as follows solves the issue:

    template <typename Func, typename... Extra> class_ &
    def_static(const char *name_, Func &&f, const Extra&... extra) {
        static_assert(!std::is_member_function_pointer<Func>::value,
                "def_static(...) called with a non-static member function pointer");
        cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
                        sibling(getattr(*this, name_, none())), extra...);

        auto tmp = staticmethod(cf);
        PyCFunctionObject *fun_ptr = (PyCFunctionObject *) cf.ptr();
        if (fun_ptr->m_ml->ml_doc) {
            tmp.attr("__doc__") = strdup(const_cast<char *>(fun_ptr->m_ml->ml_doc));
        }

        attr(cf.name()) = tmp;
        return *this;
    }

I'm hesitant to submit a PR as I don't know if this is the proper way to set the doc string of a staticmethod (I can't find any documentations on manipulating Python objects in C/C++ online).

If this turns out to be a good fix then I can submit a PR. Otherwise, just letting you know this bug exists. Having good docstring is important to me as I use a stub generation script (similar to the one in Mypy object) to generator python stub files for pybind11 libraries to make IDE programming easier.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions