How to make functions from C extension writable?

Hi!

I have a Python C extension that provides a bunch of functions. I would like to assign some __doc__ attribute to them, but I end-up with an error:

In [24]: np.char.compare_chararrays.__doc__ = "new doc"
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[24], line 1
----> 1 np.char.compare_chararrays.__doc__ = "new doc"

AttributeError: attribute '__doc__' of 'builtin_function_or_method' objects is not writable

And my guess is it’s due to the fact that functions coming from a C extension don’t have the __dict__ attribute.

Is it possible to build a C extension and make functions writable?

static PyObject *
compare_chararrays(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds)
{
...
}

static struct PyMethodDef array_module_methods[] = {
    {"compare_chararrays",
        (PyCFunction)compare_chararrays,
        METH_VARARGS | METH_KEYWORDS, NULL},
}

Is there a reason the docstring can’t be set in the C extension? That’s what ml_doc is for: Common Object Structures — Python 3.13.0 documentation

Hmm, then I wonder why they weren’t set with ml_doc in the first place but with add_newdoc instead: numpy/numpy/_core/_add_newdocs.py at 9150cace28edb9d535a144d3dbc330a0e07f1995 · numpy/numpy · GitHub

For UFuncs it was impossible so add_newdoc was used, but for extension methods?

I think for convenience? It’s annoying to do string formatting in C.

Ah, makes sense!