[Python-Dev] Sharing docstrings between the Python and C implementations of a module

Maciej Fijalkowski fijall at gmail.com
Mon Apr 15 12:17:39 CEST 2013

On Mon, Apr 15, 2013 at 9:56 AM, David Lam <david.k.lam1 at gmail.com> wrote:
> Recently I helped out on issue16954 which involved filling in docstrings
> for methods and classes in ElementTree.py
> While doing so, I tried to test my work in the interpreter like this...
>     >>> from xml.etree.ElementTree import Element
>     >>> help(Element)
> ...but found that help() showed nothing but empty strings!
> After some debugging, I found that the culprit was the
>  `from _elementtree import *` near the bottom of the module.
> Not wanting to copy & paste docstrings around,  I thought one solution
> might be to just reassign Element.__doc__ with the right docstring.
> But, it seems that you can't do that for C extensions:
>     >>> from _elementtree import Element as cElement
>     >>> cElement.__doc__ = 'correct docstring'
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     TypeError: can't set attributes of built-in/extension type
> 'xml.etree.ElementTree.Element'
> ---
> Q.  Is there way to maintain the same docstring without
>     resorting to copying and pasting it in two places?
> I tried to find an example in the source which addressed this, but
> found that the docstrings in similar cases to be largely duplicated.
> For instance, _datetimemodule.c, decimal_.c and _json.c all seem to
> exhibit this docstring copy and pastage.


NumPy uses a hack to deal with this problem. It has a small C function
that would mutate the docstring under your feet. Personally I would
prefer some sort of tagging in C source that can copy-paste stuff
instead, honestly. It does sound like a good idea to share docstrings.
Seems also relatively trivial to write a test that checks that they
stay the same.


More information about the Python-Dev mailing list